我已经开始学习 Python twisted。我有一个基本要求来映射 TCP 客户端的请求和响应。客户端可以根据某些条件随时发送任何请求,并且它期望来自服务器的该请求的特定响应。我如何映射请求-响应对。我想要的示例代码。此外,服务器可以发送不映射到任何客户端请求的任意消息。
class MSOProtocol(Protocol):
def __init__(self):
self.client_id = uuid4()
self.messagePair = collections.OrderedDict()
def connectionMade(self):
log.msg("Device connected to TSIF")
self.doOperation()
def connectionLost(self, reason):
log.msg('Device lost connection because {}'.format(reason))
def sendMessage(self, data):
log.msg('Device sending...str(msg)'.format(data))
self.transport.write(data)
def dataReceived(self, data):
log.msg('Device received {}'.format(data))
#how do I map the response with my request
def doOperation(self):
CONDITION = "rainy"
if condition == "sunny":
self.sendMessage("sunny weather")
class DeviceFactory(ClientFactory):
def buildProtocol(self, addr):
return MSOProtocol()
def main():
log.startLogging(sys.stdout)
reactor.connectTCP('127.0.0.1', 16000, DeviceFactory())
reactor.run()
if __name__ == '__main__':
main()