后台小程序开发的全方位指南
680
2022-10-23
python异步引擎Twisted实现Zinx框架
Zinx
使用Twisted引擎实现Zinx框架
server.py
from msghandler import IMsgHandlerfrom message import Messagefrom datapack import DataPackfrom server import Serverdef handleData(addr,transport): msg = Message() msg.setMsgData(b'Test msg python') msg.setMsgId(0) datapack = DataPack(msg) data = datapack.pack() transport.write(data) print('[Server] write data %r to addr %r' % (data, addr))if __name__ == '__main__': #添加不同id处理方法 routers=IMsgHandler() routers.AddRouter(0, handleData1) serve = Server(routers=routers) serve.server()
client.py
from __future__ import print_functionfrom twisted.internet import reactor, protocolfrom message import Messagefrom datapack import DataPack# a client protocolclass EchoClient(protocol.Protocol): def connectionMade(self): m=Message() s=b"Test msg" m.setMsgData(s) m.setMsgId(1) d=DataPack(m).pack() self.transport.write(d) def dataReceived(self, data): msg = Message() datapack = DataPack(msg) msglen, msgid, msgdata = datapack.unpack(data) print('[Client] receive data %r from server, len:%r , id:%r' % (msgdata,msglen, msgid)) def connectionLost(self, reason): print("connection lost")class EchoFactory(protocol.ClientFactory): protocol = EchoClient def clientConnectionFailed(self, connector, reason): print("Connection failed - goodbye!") reactor.stop() def clientConnectionLost(self, connector, reason): print("Connection lost - goodbye!") reactor.stop()# this connects the protocol to a server running on port 8000def main(): f = EchoFactory() reactor.connectTCP("localhost", 8080, f) reactor.run()# this only runs if the module was *not* importedif __name__ == '__main__': main()
config.py
class Config: Host='127.0.0.1' Port=8080 Name='Zinx Server' Version='ipv4' MaxConn=1
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~