使用Python的Twisted框架编写简单的网络客户端
Protocol
和服务器一样,也是通过该类来实现。先看一个简短的例程:
fromtwisted.internet.protocolimportProtocol fromsysimportstdout classEcho(Protocol): defdataReceived(self,data): stdout.write(data)
在本程序中,只是简单的将获得的数据输出到标准输出中来显示,还有很多其他的事件没有作出任何响应,下面
有一个回应其他事件的例子:
fromtwisted.internet.protocolimportProtocol classWelcomeMessage(Protocol): defconnectionMade(self): self.transport.write("Helloserver,Iamtheclient!/r/n") self.transport.loseConnection()
本协议连接到服务器,发送了一个问候消息,然后关闭了连接。
connectionMade事件通常被用在建立连接的事件发生时触发。关闭连接的时候会触发connectionLost事件函数
(Simple,single-useclients)简单的单用户客户端
在许多情况下,protocol仅仅是需要连接服务器一次,并且代码仅仅是要获得一个protocol连接的实例。在
这样的情况下,twisted.internet.protocol.ClientCreator提供了一个恰当的API
fromtwisted.internetimportreactor fromtwisted.internet.protocolimportProtocol,ClientCreator classGreeter(Protocol): defsendMessage(self,msg): self.transport.write("MESSAGE%s/n"%msg) defgotProtocol(p): p.sendMessage("Hello") reactor.callLater(1,p.sendMessage,"Thisissentinasecond") reactor.callLater(2,p.transport.loseConnection) c=ClientCreator(reactor,Greeter) c.connectTCP("localhost",1234).addCallback(gotProtocol)
ClientFactory(客户工厂)
ClientFactory负责创建Protocol,并且返回相关事件的连接状态。这样就允许它去做像连接发生错误然后
重新连接的事情。这里有一个ClientFactory的简单例子使用Echo协议并且打印当前的连接状态
fromtwisted.internet.protocolimportProtocol,ClientFactory fromsysimportstdout classEcho(Protocol): defdataReceived(self,data): stdout.write(data) classEchoClientFactory(ClientFactory): defstartedConnecting(self,connector): print'Startedtoconnect.' defbuildProtocol(self,addr): print'Connected.' returnEcho() defclientConnectionLost(self,connector,reason): print'Lostconnection.Reason:',reason defclientConnectionFailed(self,connector,reason): print'Connectionfailed.Reason:',reason
要想将EchoClientFactory连接到服务器,可以使用下面代码:
fromtwisted.internetimportreactor reactor.connectTCP(host,port,EchoClientFactory()) reactor.run()
注意:clientConnectionFailed是在Connection不能被建立的时候调用,clientConnectionLost是在连接关闭的时候被调用,两个是有区别的。
Reconnection(重新连接)
许多时候,客户端连接可能由于网络错误经常被断开。一个重新建立连接的方法是在连接断开的时候调用
connector.connect()方法。
fromtwisted.internet.protocolimportClientFactory classEchoClientFactory(ClientFactory): defclientConnectionLost(self,connector,reason): connector.connect()
connector是connection和protocol之间的一个接口被作为第一个参数传递给clientConnectionLost,
factory能调用connector.connect()方法重新进行连接
然而,许多程序在连接失败和连接断开进行重新连接的时候使用ReconnectingClientFactory函数代替这个
函数,并且不断的尝试重新连接。这里有一个EchoProtocol使用ReconnectingClientFactory的例子:
fromtwisted.internet.protocolimportProtocol,ReconnectingClientFactory fromsysimportstdout classEcho(Protocol): defdataReceived(self,data): stdout.write(data) classEchoClientFactory(ReconnectingClientFactory): defstartedConnecting(self,connector): print'Startedtoconnect.' defbuildProtocol(self,addr): print'Connected.' print'Resettingreconnectiondelay' self.resetDelay() returnEcho() defclientConnectionLost(self,connector,reason): print'Lostconnection.Reason:',reason ReconnectingClientFactory.clientConnectionLost(self,connector,reason) defclientConnectionFailed(self,connector,reason): print'Connectionfailed.Reason:',reason ReconnectingClientFactory.clientConnectionFailed(self,connector,reason)
AHigher-LevelExample:ircLogBot
上面的所有例子都非常简单,下面是一个比较复杂的例子来自于doc/examples目录
#twistedimports fromtwisted.words.protocolsimportirc fromtwisted.internetimportreactor,protocol fromtwisted.pythonimportlog #systemimports importtime,sys classMessageLogger: """ Anindependentloggerclass(becauseseparationofapplication andprotocollogicisagoodthing). """ def__init__(self,file): self.file=file deflog(self,message): """Writeamessagetothefile.""" timestamp=time.strftime("[%H:%M:%S]",time.localtime(time.time())) self.file.write('%s%s/n'%(timestamp,message)) self.file.flush() defclose(self): self.file.close() classLogBot(irc.IRCClient): """AloggingIRCbot.""" nickname="twistedbot" defconnectionMade(self): irc.IRCClient.connectionMade(self) self.logger=MessageLogger(open(self.factory.filename,"a")) self.logger.log("[connectedat%s]"% time.asctime(time.localtime(time.time()))) defconnectionLost(self,reason): irc.IRCClient.connectionLost(self,reason) self.logger.log("[disconnectedat%s]"% time.asctime(time.localtime(time.time()))) self.logger.close() #callbacksforevents defsignedOn(self): """Calledwhenbothassuccesfullysignedontoserver.""" self.join(self.factory.channel) defjoined(self,channel): """Thiswillgetcalledwhenthebotjoinsthechannel.""" self.logger.log("[Ihavejoined%s]"%channel) defprivmsg(self,user,channel,msg): """Thiswillgetcalledwhenthebotreceivesamessage.""" user=user.split('!',1)[0] self.logger.log("<%s>%s"%(user,msg)) #Checktoseeifthey'resendingmeaprivatemessage ifchannel==self.nickname: msg="Itisn'tnicetowhisper!Playnicewiththegroup." self.msg(user,msg) return #Otherwisechecktoseeifitisamessagedirectedatme ifmsg.startswith(self.nickname+":"): msg="%s:Iamalogbot"%user self.msg(channel,msg) self.logger.log("<%s>%s"%(self.nickname,msg)) defaction(self,user,channel,msg): """Thiswillgetcalledwhenthebotseessomeonedoanaction.""" user=user.split('!',1)[0] self.logger.log("*%s%s"%(user,msg)) #irccallbacks defirc_NICK(self,prefix,params): """CalledwhenanIRCuserchangestheirnickname.""" old_nick=prefix.split('!')[0] new_nick=params[0] self.logger.log("%sisnowknownas%s"%(old_nick,new_nick)) classLogBotFactory(protocol.ClientFactory): """AfactoryforLogBots. Anewprotocolinstancewillbecreatedeachtimeweconnecttotheserver. """ #theclassoftheprotocoltobuildwhennewconnectionismade protocol=LogBot def__init__(self,channel,filename): self.channel=channel self.filename=filename defclientConnectionLost(self,connector,reason): """Ifwegetdisconnected,reconnecttoserver.""" connector.connect() defclientConnectionFailed(self,connector,reason): print"connectionfailed:",reason reactor.stop() if__name__=='__main__': #initializelogging log.startLogging(sys.stdout) #createfactoryprotocolandapplication f=LogBotFactory(sys.argv[1],sys.argv[2]) #connectfactorytothishostandport reactor.connectTCP("irc.freenode.net",6667,f) #runbot reactor.run()
ircLogBot.py连接到了IRC服务器,加入了一个频道,并且在文件中记录了所有的通信信息,这表明了在断开连接进行重新连接的连接级别的逻辑以及持久性数据是被存储在Factory的。
PersistentDataintheFactory
由于Protocol在每次连接的时候重建,客户端需要以某种方式来记录数据以保证持久化。就好像日志机器人一样他需要知道那个那个频道正在登陆,登陆到什么地方去。
fromtwisted.internetimportprotocol fromtwisted.protocolsimportirc classLogBot(irc.IRCClient): defconnectionMade(self): irc.IRCClient.connectionMade(self) self.logger=MessageLogger(open(self.factory.filename,"a")) self.logger.log("[connectedat%s]"% time.asctime(time.localtime(time.time()))) defsignedOn(self): self.join(self.factory.channel) classLogBotFactory(protocol.ClientFactory): protocol=LogBot def__init__(self,channel,filename): self.channel=channel self.filename=filename
当protocol被创建之后,factory会获得他本身的一个实例的引用。然后,就能够在factory中存在他的属性。
更多的信息:
本文档讲述的Protocol类是IProtocol的子类,IProtocol方便的被应用在大量的twisted应用程序中。要学习完整的IProtocol接口,请参考API文档IProtocol.
在本文档一些例子中使用的trasport属性提供了ITCPTransport接口,要学习完整的接口,请参考API文档ITCPTransport
接口类是指定对象有什么方法和属性以及他们的表现形式的一种方法。参考Components:InterfacesandAdapters文档