0X04-Twisted Teactor TCP Server
Twisted Teactor TCP Server
#! /usr/bin/env python from twisted.internet import protocol,reactor from time import ctime ''' 这是一个时间戳TCP服务器,它使用了Twisted Internet类 Twisted是用Python实现的基于事件驱动的网络引擎框架:https://www.cnblogs.com/silence-cho/p/9898984.html ''' PORT = 21567 ''' 1;reactor是twisted异步框架中的核心组件,是一个基于select,poll或epoll的事件循环,其监听socket的状态,当socket状态有变化时(有新的连接请求,或接受到数据等)时,调用相应的组件来进行处理。 2;Factory: 主要用来创建protocol,也可以定义其他操作 3;Protocol:主要用来处理连接建立和断开时的操作,以及数据的接受和发送操作 ''' class TSServProtocol(protocol.Protocol): def connectionMade(self): clnt = self.clnt = self.transport.getPeer().host print('...connected from:',clnt) def dataReceived(self, data): self.transport.write(data) factory = protocol.Factory() factory.protocol = TSServProtocol print('waiting for connection...') reactor.listenTCP(PORT,factory) reactor.run() ''' 英语翻译: 1;protocol 协议 2;reactor 反应器 '''
Twisted Teactor TCP Client
#! /usr/bin/env python from twisted.internet import protocol,reactor HOST = 'localhost' PORT = 21567 class TSClntProtocol(protocol.Protocol): def sendData(self): data = input('> ') if data: print("...sending %s..." % data) self.transport.write(data) else: self.transport.loseConnection() def connectionMade(self): self.sendData() def dataReceived(self, data): print(data) self.sendData() class TSClntFactory(property.ClientFactory): protocol = TSClntProtocol clientConnectionLost = clientConnectionFailed = lambda self ,connector,reason:reactor.stop() reactor.connectTcp(HOST,PORT,TSClntFactory()) reactor.run()