简体   繁体   English

扭曲:如何通过扭曲的客户端在单个端口上发送消息?

[英]Twisted: How to send messages by twisted client on single port?

I may send messages to server from twisted client by calling connector.connect() . 我可以通过调用connector.connect()从扭曲的客户端向服务器发送消息。 But clients will be made on different ports. 但是客户端将在不同的端口上建立。 Following code is demonstrated this case: 下面的代码演示了这种情况:

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

And my twisted server say me: 我扭曲的服务器说:

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

Clients has different ports - 41930, 41931, etc. How send messages from twisted client with single port? 客户端具有不同的端口-41930、41931等。如何从具有单个端口的双绞线客户端发送消息?

You can use the bindAddress parameter in either connectTCP , clientFromString , TCP4ClientEndpoint , or TCP6ClientEndpoint . 您可以在connectTCPclientFromStringTCP4ClientEndpointTCP6ClientEndpoint使用bindAddress参数。 Using your example, your code would look like: 使用您的示例,您的代码如下所示:

reactor.connectTCP(SERVER_HOST, SERVER_PORT, EchoFactory(), bindAddress=('127.0.0.1',9999))

I would advise you to avoid this if it's not absolutely necessary because the port may be in use by another process and will cause an exception. 如果不是绝对必要的话,我建议您避免这种情况,因为该端口可能正在被另一个进程使用,并且会导致异常。 It's better for the OS to chose the ip:port for your app to bind to. 对于OS,最好为您的应用选择要绑定到的ip:port。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM