歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> 使用Twisted編寫服務器

使用Twisted編寫服務器

日期:2017/3/1 9:48:07   编辑:Linux編程

Twisted使用異步的方式處理數據,網絡中有事件到達時,協議作出對事件的響應,並調用協議裡面的方法,比如loseConnection()用於斷開連接,abortConection()用於強制終止連接,connectionMade()用於建立連接。使用Twisted編寫網絡編程程序,需要進行一下步驟:(1)定義協議類,它繼承自protocol,(2)定義factory類,它用於實例化協議類的對象,(3)定義reactor,啟動reactor 。

下面是使用Twisted的簡單服務器:

#!/usr/bin/env python
from twisted.internet import reactor
from twisted.internet.protocol import Protocol,Factory
class Handle(Protocol):
def connectionMade(self):
print self.transport.client,'connected'
def connectionLost(self,reason):
print self.transport.client,'disconnected'
def dataRecieved(self,data):
self.transport.write(data)
factory=Factory()
factory.protocol=Handle
reactor.listenTCP(10000,factory)
reactor.run()

然後再編寫客戶端程序,就可以測試這段服務器代碼了。

Copyright © Linux教程網 All Rights Reserved