twisted 學習筆記二:建立一個簡單TCP客戶端

 1 #coding=utf-8
 2 
 3 from twisted.internet import reactor,protocol
 4 
 5 class QuickClient(protocol.Protocol):
 6     def connectionMade(self):
 7         print dir(self.transport.getPeer())
 8         print "port:%s type:%s "%(self.transport.getPeer().port, self.transport.getPeer().type)
 9         print "connection to ",self.transport.getPeer().host
10 
11 
12 class BasicClientFactory(protocol.ClientFactory):
13     protocol = QuickClient
14     def clientConnectionLost(self, connector, reason):
15         print "connection lost ",reason.getErrorMessage()
16         reactor.stop()
17     def clientConnectionFailed(self, connector, reason):
18         print "connection failed ",reason.getErrorMessage()
19         reactor.stop()
20 
21 
22 reactor.connectTCP('www.google.com', 80, BasicClientFactory())
23 reactor.run()
connectionMade:連接成功後自動調用
Factory的做用是管理鏈接事件
clientConnectionLost:鏈接斷開或丟失時調用
clientConnectionFailed:鏈接失敗時調用

transport爲Protocol一個內建屬性 getPeer 對象包含有鏈接信息(域名、端口、類型(TCP,UDP))
相關文章
相關標籤/搜索