# -*- coding:cp936 -*-
#!/usr/bin/env python
"""
客户端的几个事件响应
startConnecting 正在连接服务器
buildProtocol 已连接上服务器,创建Protocol
clientConnectionLost 与主机失去连接
clientConnectionFailed 与主机连接失败
"""
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import ClientFactory
from twisted.internet import reactor
from sys import stdout
class Echo(Protocol):
def dataReceived(self,data):
stdout.write(data)
class EchoClientFactory(ClientFactory):
def startedConnecting(self,connector):
print("Start to connect")
def buildProtocol(self,addr):
print("build protocol")
return Echo()
def clientConnectionLost(self,connector,reason):
print("client connection lost" + str(reason))
def clientConnectionFailed(self,connector,reason):
print("client connection failed" + str(reason))
reactor.connectTCP("localhost",8007,EchoClientFactory())
reactor.run()
|