我已经开始学习Python扭曲了。我对映射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()