Transports
Transport代表著兩個(gè)通過(guò)網(wǎng)絡(luò)通信的端對(duì)端的連接,Transports負(fù)責(zé)描述連接的細(xì)節(jié)部分,如流或者數(shù)據(jù)包導(dǎo)向,流量控制和可靠性,TCP,UDP和Unix的套接字是Transpos的例子。他們被設(shè)計(jì)為'最大可重用的最小功能單元'并且其余協(xié)議實(shí)現(xiàn)分離,允許許多協(xié)議使用相同類(lèi)型的傳輸。
Transports實(shí)現(xiàn)了ITransport接口。具有以下幾種方法:
write--- 按照非阻塞的方式按順序?qū)⒁恍?shù)據(jù)寫(xiě)入物理連接
writeSequence---將一個(gè)字符串列表寫(xiě)入物理連接
loseConnection---寫(xiě)入所有掛起的數(shù)據(jù),然后關(guān)閉連接
getPeer---得到此連接的遠(yuǎn)程地址
getHost---得到連接這一端的地址
Transports從protocols中解耦也使得測(cè)試這兩層更加容易
Protocols
Protocols描述了如何異步處理網(wǎng)絡(luò)事件。其中HTTP,DNS和IMAP是應(yīng)用協(xié)議的示例。
Protocols實(shí)現(xiàn)了IProtocol接口,具體包括以下方法:
makeConnection---創(chuàng)建一個(gè)連接綁定一個(gè)transport和一個(gè)server
connectionMade---在連接創(chuàng)建時(shí)被調(diào)用
dataReceived---在接收到數(shù)據(jù)是被調(diào)用
connectionLost---在斷開(kāi)連接時(shí)被調(diào)用
對(duì)于reactor、transport和protocols之間的關(guān)系,最好的方法就是用一個(gè)例子來(lái)描繪,下面給出一個(gè)示例(Server+client)
首先是一個(gè)Server實(shí)現(xiàn):
from twisted.internet import protocol, reactor
class Echo(protocol.Protocol):
def dataReceived(self, data):
# 一旦有數(shù)據(jù)到來(lái)就返回一個(gè)回應(yīng)
self.transport.write(data)
class EchoFactory(protocol.Factory):
def buildProtocol(self, addr):
return Echo()
reactor.listenTCP(8000, EchoFactory())
reactor.run()
然后是一個(gè)客戶端
from twisted.internet import reactor, protocol
class EchoClient(protocol.Protocol):
def connectionMade(self):
self.transport.write("hello, world!")
def dataReceived(self, data):
print "Server said:", data
self.transport.loseConnection()
def connectionLost(self, reason):
print "connection lost"
class EchoFactory(protocol.ClientFactory):
def buildProtocol(self, addr):
return EchoClient()
def clientConnectionFailed(self, connector, reason):
print "Connection failed - goodbye!"
reactor.stop()
def clientConnectionLost(self, connector, reason):
print "Connection lost - goodbye!"
reactor.stop()
reactor.connectTCP("localhost", 8000, EchoFactory())
reactor.run()
上述代碼的描述:
運(yùn)行服務(wù)器腳本啟動(dòng)偵聽(tīng)端口8000上的連接的TCP服務(wù)器。服務(wù)器使用Echo協(xié)議(自定義),并通過(guò)TCP傳輸寫(xiě)出數(shù)據(jù)。
運(yùn)行客戶端與服務(wù)端建立TCP連接,回應(yīng)服務(wù)器響應(yīng),然后終止連接并停止reactor。
Factory主要用于生產(chǎn)連接兩端的協(xié)議實(shí)例
Transports是異步雙向的
connectTCP負(fù)責(zé)與reactor注冊(cè)回調(diào),以便在數(shù)據(jù)可以從socket上讀取時(shí)得到通知。
by---http://www.aosabook.org/en/twisted.html
將Twisted的知識(shí)再系統(tǒng)深入學(xué)習(xí)一遍。。。。