gpt4 book ai didi

python - 如果忙于扭曲,如何在另一个端口上收听

转载 作者:太空宇宙 更新时间:2023-11-04 01:28:06 25 4
gpt4 key购买 nike

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?

最佳答案

捕获 reactor.listenUDP() 引发的 twisted.internet.error.CannotListenError 并在循环中再次尝试下一个端口:

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()

关于python - 如果忙于扭曲,如何在另一个端口上收听,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16229850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com