from twisted.internet import protocol, reactor, task
class peer(protocol.DatagramProtocol):
def sendJoin(self):
self.transport.write('Join',("127.0.0.1", 8001))
def startProtocol(self):
self.sendJoin()
reactor.listenUDP(8002, peer())#if this is busy, listen on next available port
reactor.run()
如果某个其他对等端已经在侦听端口,那么如何在另一个端口上侦听,例如8003?
答案 0 :(得分:3)
抓住twisted.internet.error.CannotListenError
引发的reactor.listenUDP()
,然后再循环播放下一个端口:
from twisted.internet import protocol, reactor, task
import twisted.internet.error
class peer(protocol.DatagramProtocol):
def sendJoin(self):
self.transport.write('Join',("127.0.0.1", 8001))
def startProtocol(self):
self.sendJoin()
# just to make sure ports 8002 and 8003 will be in use
reactor.listenUDP(8002, peer())
reactor.listenUDP(8003, peer())
# try all ports between [8002..8999]
for port in range(8002, 9000):
try:
reactor.listenUDP(port, peer())
print "Listening on port %d" % port
break
except twisted.internet.error.CannotListenError, ex:
print "Port is %d busy: %s" % (port, ex)
continue
reactor.run()