python -- twisted初探
Twisted是用python实现的基于事件驱动的网络引擎框架。
初步使用twisted
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 from twisted.internet import protocol 5 from twisted.internet import reactor 6 7 class Echo(protocol.Protocol): 8 def dataReceived(self, data): 9 self.transport.write(bytes("I am server | %s" %data.decode('utf8'),'utf8')) 10 11 def main(): 12 factory = protocol.ServerFactory() 13 factory.protocol = Echo 14 reactor.listenTCP(9999,factory,interface='localhost') 15 reactor.run() 16 17 if __name__ == '__main__': 18 print("\033[32;1m server is waiting... \033[0m") 19 main()
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
1 #!/usr/bin/env python 2 # -*- coding: utf-8 -*- 3 4 from twisted.internet import protocol 5 from twisted.internet import reactor 6 7 8 class EchoClient(protocol.Protocol): 9 def connectionMade(self): 10 self.transport.write(bytes("hello root",'utf8')) 11 12 def dataReceived(self, data): 13 print("Server said:",data.decode('utf8')) 14 self.transport.loseConnection() 15 16 def connectionLost(self,reason): 17 print("connection lost") 18 19 20 class EchoFactory(protocol.ClientFactory): 21 protocol = EchoClient 22 23 def clientConnectionFailed(self, connector, reason): 24 print("Connection failed - goodbye!") 25 reactor.stop() 26 27 def clientConnectionLost(self, connector, reason): 28 print("Connection lost - goodbye!") 29 30 31 def main(): 32 f = EchoFactory() 33 reactor.connectTCP('localhost',9999,f) 34 reactor.run() 35 36 if __name__ == '__main__': 37 main() 38
非常好的twisted入门介绍文章: http://blog.csdn.net/hanhuili/article/details/9389433
借用大神的教程,以便自己学习:
python twisted教程 一,异步编程
python twisted教程 二:缓慢的诗
python twisted教程 三–开始twisted
python twised系列教程四–twisted Poetry client
twisted系列教程五–改进twisted poetry client
twisted系列教程六–继续重构twisted poetry client
twisted系列教程七–小插曲,延迟对象
twisted系列教程八–延迟的诗
twisted系列教程九–Deferred 的第二个小插曲
twisted系列教程十–可以变化的诗
twisted系列教程十一 — 一个twisted 的服务端
twisted系列教程十二–为server 增加一个service
twisted系列教程十三–deferred 中的deferred
twisted系列教程十四— pre-fireed deferred
twisted系列教程十五–测试twisted代码
twisted系列教程十六–twisted守护进程
twisted系列教程十七–用inlineCallbacks来管理callbacks
twisted系列教程十八–异步操作的并行运行
twisted系列教程十九–cancel deferred