4
我试图修改Python Twisted-UDP examples以使用UDP广播。我可以从客户端发送消息并在服务器上接收消息,但是它不会发送消息。扭曲的Python:UDP广播(简单回声服务器)
客户:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
from socket import SOL_SOCKET, SO_BROADCAST
class EchoClientDatagramProtocol(DatagramProtocol):
strings = [
"Hello, world!",
"What a fine day it is.",
"Bye-bye!"
]
def startProtocol(self):
self.transport.socket.setsockopt(SOL_SOCKET, SO_BROADCAST, True)
self.transport.connect("255.255.255.255", 8000)
self.sendDatagram()
def sendDatagram(self):
if len(self.strings):
datagram = self.strings.pop(0)
self.transport.write(datagram)
else:
reactor.stop()
def datagramReceived(self, datagram, host):
print 'Datagram received: ', repr(datagram)
self.sendDatagram()
def main():
protocol = EchoClientDatagramProtocol()
#0 means any port
t = reactor.listenUDP(0, protocol)
reactor.run()
if __name__ == '__main__':
main()
服务器:
from twisted.internet.protocol import DatagramProtocol
from twisted.internet import reactor
class EchoUDP(DatagramProtocol):
def datagramReceived(self, datagram, address):
print "Received from address: " + str(address)
print str(datagram)
self.transport.write(datagram, address)
print "Finished sending reply."
print "Starting server."
reactor.listenUDP(8000, EchoUDP())
reactor.run()
控制台输出:
Server:
Starting server.
Received from address ('192.168.1.137', 53737)
Hello, world!
Finished sending reply.
Client:
no output.
您是不是指'main'是'EchoClientDatagramProtocol'中的函数,还是这是格式化问题? – jozzas
@jozzas:格式问题,我的道歉。我编辑了上面的代码。 – firefly2442