您的位置:首页 > 理论基础 > 计算机网络

twisted 学习笔记二:创建一个简单TCP客户端

2013-07-24 17:40 567 查看
#coding=utf-8

fromtwisted.internetimportreactor,protocol

classQuickClient(protocol.Protocol):
defconnectionMade(self):
printdir(self.transport.getPeer())
print"port:%stype:%s"%(self.transport.getPeer().port,self.transport.getPeer().type)
print"connectionto",self.transport.getPeer().host

classBasicClientFactory(protocol.ClientFactory):
protocol=QuickClient
defclientConnectionLost(self,connector,reason):
print"connectionlost",reason.getErrorMessage()
reactor.stop()
defclientConnectionFailed(self,connector,reason):
print"connectionfailed",reason.getErrorMessage()
reactor.stop()

reactor.connectTCP('www.google.com',80,BasicClientFactory())
reactor.run()


connectionMade:链接成功后自动调用
Factory的作用是管理连接事件

clientConnectionLost:连接断开或丢失时调用

clientConnectionFailed:连接失败时调用

transport为Protocol一个内建属性getPeer对象包含有连接信息(域名、端口、类型(TCP,UDP))


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐