Twisted:在connectTCP之后关闭连接而不会丢失其他连接

pau*_*ago 2 python tcp twisted

我是Twisted的新手,我正在试图弄清楚如何实现以下内容.我有一个服务器,它接收来自客户端的消息.但是,此服务器在收到消息后会将消息从客户端发送到另一台服务器.所以它看起来像:

Client --->   Server1  --->   Server2
Run Code Online (Sandbox Code Playgroud)

所以Server1本质上既充当服务器又充当客户端.但是,在Server1向Server2发送信息后,我想断开Server1与Server2的连接.我不知道怎么能这样做.

我现在所做的是客户端向Server1发送信息.然后我稍微修改输入,然后reactor.connectTCP()成功连接并向Server2发送信息.我的麻烦是如何在不必完全关闭Server1的情况下关闭连接.我尝试使用transport.loseConnection( )但是当它从Server2断开连接时关闭Server1.

我正在考虑reactor.spawnProcess()以某种方式使用,但我无法让它工作.从我看到的,当我关闭连接时,它关闭了进程,所以如果我可以使用另一个进程connectTCP,它不应该影响其他进程.

这是我的代码

import time, datetime
import re
from twisted.internet import stdio, reactor, protocol
from twisted.protocols import basic

result = 'The AT message is unavailable (no previous talk with client)'

class DataForwardingProtocol(protocol.Protocol):
    def __init__(self):
        self.output = None
        self.normalizeNewlines = False

    def dataReceived(self, data):
        if self.normalizeNewlines:
            data = re.sub(r"(\r\n|\n)", "\r\n", data)
        if self.output:
            self.output.write(data)

class StdioProxyProtocol(DataForwardingProtocol):
    global result
    def connectionMade(self):
        inputForwarder = DataForwardingProtocol()
        inputForwarder.output = self.transport
        inputForwarder.normalizeNewlines = True
        stdioWrapper = stdio.StandardIO(inputForwarder)
        self.output = stdioWrapper
        self.transport.write(result)
        self.transport.loseConnection( )

class StdioProxyFactory(protocol.ClientFactory):
    protocol = StdioProxyProtocol

    def clientConnectionLost(self, transport, reason):
        reactor.stop()

    def clientConnectionFailed(self, transport, reason):
        print reason.getErrorMessage()
        reactor.stop()

class EchoProtocol(basic.LineReceiver):

    def dataReceived(self, line):
      #Do stuff with the input sent from the client.  This is irrelevant to my problem.
                #UPDATE OTHER SERVERS
                reactor.connectTCP('localhost', 12771, StdioProxyFactory())   

class EchoServerFactory(protocol.ServerFactory):
    protocol = EchoProtocol

if __name__ == "__main__":
    port = 12770
    reactor.listenTCP(port, EchoServerFactory( ))
    reactor.run( )
Run Code Online (Sandbox Code Playgroud)

谢谢!

the*_*aul 5

您的Server1正在关闭,因为reactor.stop()您使用工厂的clientConnectionLost()方法transport.loseConnection()调用,而不是因为调用.一旦第一个传出连接丢失,您可能不希望关闭整个反应器.