我是Twisted的新手,我試圖弄清楚如何實現以下內容。 我有一臺服務器,它從客戶端接收消息。然而,該服務器在收到消息後將消息從客戶端發送到另一臺服務器。 所以它看起來是這樣的:在本質上扭曲:connectTCP後關閉連接,而不會丟失其他連接
Client ---> Server1 ---> Server2
所以Server1上,同時充當服務器和客戶端。但是,在Server1向Server2發送信息之後,我想要將Server1從Server2斷開連接。我不知道我該如何做到這一點。
我現在的工作是客戶端發送信息到Server1。然後我修改輸入一點,然後做reactor.connectTCP()
成功連接併發送信息到服務器2。我的麻煩是如何關閉連接而不必完全關閉Server1。我嘗試使用transport.loseConnection()
,但是當Server1與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()
謝謝!