listenTCP
返回IListeningPort
,它有一個getHost()
方法,該方法將port
返回給對象。例如:
>>> from twisted.internet import reactor
>>> from twisted.internet.protocol import Factory
>>> port = reactor.listenTCP(0, Factory())
>>> port.getHost().port
55791
然而,直到它開始privilegedStartService
TCPServer
不叫listenTCP
。另外,IListeningPort
實際上並未通過公開API公開。所以,你需要編寫自己的Service
。幸運的是,這樣做很容易; TCPServer
不會做太多。你只需要編寫一個報告它的端口的地方,一旦它開始收聽。這裏有一個例子:
from twisted.internet import reactor
from twisted.application.service import Service
class PortReporter(Service, object):
def __init__(self, factory, reportPort):
self.factory = factory
self.reportPort = reportPort
def privilegedStartService(self):
self.listeningPort = reactor.listenTCP(0, self.factory)
self.reportPort(self.listeningPort.getHost().port)
return super(PortReporter, self).privilegedStartService()
def stopService(self):
self.listeningPort.stopListening()
return super(PortReporter, self).stopService()
您可以在TAC文件,然後用這個,像這樣:如果你需要端點要做到這一點,這裏是我的實現有一個輕微的調整
from twisted.internet.protocol import Factory
from twisted.application.service import Application
application = Application("test")
def showPortNumber(n):
print("The port number is: %d" % (n,))
PortReporter(Factory(), showPortNumber).setServiceParent(application)
+1,努力:) – mouad
+1爲最佳答案。 –