2
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?

4

1 回答 1

3

在循环中捕获 raise twisted.internet.error.CannotListenErrorbyreactor.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()
于 2013-04-26T07:36:53.350 回答