python -- twisted初探

Twisted是用python實現的基於事件驅動的網絡引擎框架。python

初步使用twistedreact

 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()
echo_server
 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     
echo_client

 

很是好的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
相關文章
相關標籤/搜索