[英]Send commands to twisted server
我有一個簡單的雙絞線TCP服務器,用於從另一個應用程序發送和接收數據。 建立連接后,我就可以向該應用程序通信並向其發送消息。
我希望能夠在何時以及將什么內容發送到第三方應用程序時(而不是在連接時)使用外部模塊命令。 例如,這是我的服務器代碼:
from twisted.internet import reactor, protocol
# Twisted
class Tcp(protocol.Protocol):
def dataReceived(self, data):
self.transport.write(data)
print 'data received: ', data
# do something with data
def connectionMade(self, msg):
# Want to only transport message when I command not immediately when connected
self.transport.write(msg)
class TcpFactory(protocol.Factory):
def buildProtocol(self, addr):
return Tcp()
reactor.listenTCP(8001, TcpFactory())
reactor.run()
我還有另一個模塊(由GUI界面操作),該模塊定義要發送的消息,並且需要將該消息作為“ msg”傳遞給connectionMade
做這個的最好方式是什么?
您的第3方呼叫將在connectionMade
內部進行,並且不應直接呼叫。 connectionMade
是一個Twisted回調,它在那里表示客戶端在另一側。 由您決定之后會發生什么。 因此,您可以執行一系列采取self.transport
(包含相關客戶數據)的Deferred
s / callbacks之類的操作。 在這些系列的回調中,您將擁有
這是要點:
def connectionMade(self):
d = Deferred()
d.addCallback(self.thirdPartyComm).addErrBack(self.handleError)
d.addCallback(sendMsg)
d.callback(self.transport)
def thirdPartyComm(self, transport):
# logic for talking to 3rd party goes here
# 3rd party should validate the client then provide a msg
# or raise exception if client is invalid
return msg
def handleError(self, error):
# something went wrong, kill client connection
self.transport.loseConnection()
def sendMsg(self, msg):
self.transport.write(msg)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.