[英]Twisted: How to send messages by twisted client on single port?
我可以通過調用connector.connect()
從扭曲的客戶端向服務器發送消息。 但是客戶端將在不同的端口上建立。 下面的代碼演示了這種情況:
SERVER_HOST = 'localhost'
SERVER_PORT = '5000'
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("message")
self.transport.loseConnection()
class EchoFactory(protocol.ClientFactory):
def buildProtocol(self, addr):
print('Connected.')
return EchoClient()
def clientConnectionLost(self, connector, reason):
print('Lost connection. Reason:', reason)
connector.connect()
def main():
reactor.connectTCP(SERVER_HOST, SERVER_PORT, EchoFactory())
reactor.run()
我扭曲的服務器說:
Packet received, client 127.0.0.1:41930, size: 7
Connection lost
Packet received, client 127.0.0.1:41931, size: 7
Connection lost
Packet received, client 127.0.0.1:41932, size: 7
Connection lost
Packet received, client 127.0.0.1:41933, size: 7
客戶端具有不同的端口-41930、41931等。如何從具有單個端口的雙絞線客戶端發送消息?
您可以在connectTCP
, clientFromString
, TCP4ClientEndpoint
或TCP6ClientEndpoint
使用bindAddress
參數。 使用您的示例,您的代碼如下所示:
reactor.connectTCP(SERVER_HOST, SERVER_PORT, EchoFactory(), bindAddress=('127.0.0.1',9999))
如果不是絕對必要的話,我建議您避免這種情況,因為該端口可能正在被另一個進程使用,並且會導致異常。 對於OS,最好為您的應用選擇要綁定到的ip:port。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.