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))
 
posted @ 2013-07-24 17:40  践道者  阅读(1558)  评论(0编辑  收藏  举报