網(wǎng)站建設(shè)新趨勢國內(nèi)新聞大事
編寫客戶端程序
twisted
框架是設(shè)計的十分靈活的,他可以讓你編寫強大的客戶端程序。而是現(xiàn)在這種靈活性的代價僅僅是在編寫客戶端程序的時候多添加了幾層。
實際上,你真正實現(xiàn)協(xié)議的解析和處理的是Protocol
類。這個類一般是派生自twisted.internet.protocol.Protocol
.
Simple, single-use clients
在大多數(shù)的情況下,protocol
只需要連接到服務(wù)器一次,程序也只是想得到一個實例對象即可。在這種情況下,twisted.internet.endpoints
為我們提供了適當(dāng)?shù)?code>API。
from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internte.endpoints import TCP4ClientEndpoint, connectProtocolclass Greeter(Protocol):def sendMessage(self, msg):self.transport.write("message is : %s " % (msg))def getProtocol(p):p.sendMessage("Hello")reactor.callLater(1, p.sendMessage, "This is sent in a second.")reactor.callLater(2, p.transport.loseConnection)point = TCP4ClientEndpoint(reactor, "127.0.0.1", 1234)
d = connectProtocol(point, Greeter())
d.addCallback(getProtocol)
reactor.run()
不管client endpoint
的類型是什么,建立一個新的連接的方式就是簡單地將它和一個Protocol
的實例對象傳給connectProtocol
.這就意味著你不需要更改過多的代碼就可以改變你創(chuàng)建連接的方式。
一個簡單的例子就是:如果你想在SSL的協(xié)議下運行上述的Greeter,你只需要用SSL4ClientEndpoint替代TCP4ClientEndpoint即可
為了很好滴利用這個優(yōu)點,用來開啟一個連接的函數(shù)和方法通常是將一個endpoint
作為一個參數(shù),而這endpoint
由他的調(diào)用者來構(gòu)建,而不是簡單地傳入host
和port
,讓函數(shù)和方法自己來構(gòu)建endpoint
對象實例。
ClientFactory
盡管如此,仍然有很多代碼使用了較低級的api,還有一些特性(如自動重連接)還沒有通過endpoint
重新實現(xiàn),所以在某些情況下使用它們可能更方便。
為了使用較低級的api,你需要直接去調(diào)用reactor.connect*
方法。在這種情況下,你就需要ClientFactory
來幫助你完成任務(wù)。ClientFactory
同樣可以創(chuàng)建Protocol
實例對象和接收與網(wǎng)絡(luò)連接狀態(tài)相關(guān)的事件。這就使得其具有了在發(fā)生網(wǎng)絡(luò)連接錯誤的時候,重新連接的能力。下面是一個簡單的例子:
from twisted.internet.protocol import Protocol, ClientFactory
from sys import stdoutclass Echo(Protocol):def dataReceived(self, data):stdout.write(bytes.decode(data))class EchoClientFactory(ClientFactory):def startedConnecting(self, connector):print("Started to connect.")def buildProtocol(self, addr):print("Connected.")return Echo()def clientConnectionLost(self, connector, reason):print('Lost the connection for reason : %s .' % reason)def clientConnectionFailed(self, connector, reason):print('Connection failed for reason : %s .' % reason)from twisted.internet import reactor
host = '127.0.0.1'
port = 8123
reactor.connectTCP(host, port, EchoClientFactory())
reactor.run()
啟動之前設(shè)計的聊天服務(wù),然后執(zhí)行上述代碼,即可得到連接成功:
---------服務(wù)啟動后---------------------------
E:\desktop\TwisedLearn\simple_examples>python ClientConnectToServer.py
Started to connect.
Connected.
What your name?
---------服務(wù)終止后---------------------------
E:\desktop\TwisedLearn\simple_examples>python ClientConnectToServer.py
Started to connect.
Connection failed for reason : [Failure instance: Traceback (failure with no
frames): <class 'twisted.internet.error.ConnectionRefusedError'>: Connection
was refused by other side: 10061: 由于目標(biāo)計算機積極拒絕,無法連接。.
] .
Reactor Client APIs
connectTCP()
IReactorTCP.connectTCP
提供了IPv4和IPv6兩種客戶端。
詳細(xì)的API參考 IReactorTCP.connectTCP.
Reconnection
客戶端的連接經(jīng)常會因為網(wǎng)絡(luò)連接的各種問題而發(fā)生中斷。當(dāng)連接斷開的時候,一種在斷開連接重新連接的方式是通過調(diào)用connector.connect()
.
from twisted.internet.protocol import ClientFactoryclass EchoClientFactory(ClientFactory):def clientConnectionLost(self, connector, reason):connector.connect()
connector
作為這個接口的第一個參數(shù)傳入,處在一個連接和一個protocol
之間。當(dāng)這個網(wǎng)絡(luò)連接失敗的時候,這個factory
接收到一個connectionLost
事件,隨之調(diào)用connector.connect()
從斷開的地方重新開始連接。
然而,在大多數(shù)的情況下,我們希望使用一個實現(xiàn)了ReconnectingClientFactory
接口的一個方法,它會在連接丟失或失敗時嘗試重新連接,并以指數(shù)級延遲重復(fù)的重新連接嘗試。下面是一個例子:
from twisted.internet.protocol import Protocol, ReconnectingClientFactory
from sys import stdoutclass Echo(Protocol):def dataReceived(self, data):stdout.write(data)class EchoClientFactory(ReconnectingClientFactory):def startedConnecting(self, connector):print('Started to connect.')def buildProtocol(self, addr):print('Connected.')print('Resetting reconnection delay.')self.resetDelay()return Echo()def clientConnectionLost(self, connector, reason):print('Lost connection. Reason: %s' % reason)ReconnectingClientFactory.clientConnectionLost(self, connector, reason)def clientConnectionFailed(self, connector, reason):print('Connection failed. Reason:', reason)ReconnectingClientFactory.clientConnectionFailed(self, connector,reason)
A Higher-Level Example: ircLogBot
# Copyright (c) Twisted Matrix Laboratories.
# See LICENSE for details."""
An example IRC log bot - logs a channel's events to a file.If someone says the bot's name in the channel followed by a ':',
e.g.<foo> logbot: hello!the bot will reply:<logbot> foo: I am a log botRun this script with two arguments, the channel name the bot should
connect to, and file to log to, e.g.:$ python ircLogBot.py test test.logwill log channel #test to the file 'test.log'.To run the script:$ python ircLogBot.py <channel> <file>
"""from __future__ import print_function# twisted imports
from twisted.words.protocols import irc
from twisted.internet import reactor, protocol
from twisted.python import log# system imports
import time, sysclass MessageLogger:"""獨立的日志模塊(應(yīng)用和協(xié)議程序的分離是一個很好的事情)"""def __init__(self, file):self.file = filedef log(self, message):"""向文件中寫入信息"""timestamp = time.strftime("[%H:%M:%S]", time.localtime(time.time()))self.file.write('%s %s\n' % (timestamp, message))self.file.flush()def close(self):self.file.close()class LogBot(irc.IRCClient):"""A logging IRC bot."""nickname = "twistedbot"def connectionMade(self):irc.IRCClient.connectionMade(self)self.logger = MessageLogger(open(self.factory.filename, "a"))self.logger.log("[connected at %s]" % time.asctime(time.localtime(time.time())))def connectionLost(self, reason):irc.IRCClient.connectionLost(self, reason)self.logger.log("[disconnected at %s]" % time.asctime(time.localtime(time.time())))self.logger.close()# callbacks for eventsdef signedOn(self):"""Called when bot has successfully signed on to server."""self.join(self.factory.channel)def joined(self, channel):"""This will get called when the bot joins the channel."""self.logger.log("[I have joined %s]" % channel)def privmsg(self, user, channel, msg):"""This will get called when the bot receives a message."""user = user.split('!', 1)[0]self.logger.log("<%s> %s" % (user, msg))# Check to see if they're sending me a private messageif channel == self.nickname:msg = "It isn't nice to whisper! Play nice with the group."self.msg(user, msg)return# Otherwise check to see if it is a message directed at meif msg.startswith(self.nickname + ":"):msg = "%s: I am a log bot" % userself.msg(channel, msg)self.logger.log("<%s> %s" % (self.nickname, msg))def action(self, user, channel, msg):"""This will get called when the bot sees someone do an action."""user = user.split('!', 1)[0]self.logger.log("* %s %s" % (user, msg))# irc callbacksdef irc_NICK(self, prefix, params):"""Called when an IRC user changes their nickname."""old_nick = prefix.split('!')[0]new_nick = params[0]self.logger.log("%s is now known as %s" % (old_nick, new_nick))# For fun, override the method that determines how a nickname is changed on# collisions. The default method appends an underscore.def alterCollidedNick(self, nickname):"""Generate an altered version of a nickname that caused a collision in aneffort to create an unused related name for subsequent registration."""return nickname + '^'class LogBotFactory(protocol.ClientFactory):"""A factory for LogBots.A new protocol instance will be created each time we connect to the server."""def __init__(self, channel, filename):self.channel = channelself.filename = filenamedef buildProtocol(self, addr):p = LogBot()p.factory = selfreturn pdef clientConnectionLost(self, connector, reason):"""If we get disconnected, reconnect to server."""connector.connect()def clientConnectionFailed(self, connector, reason):print("connection failed:", reason)reactor.stop()if __name__ == '__main__':# initialize logginglog.startLogging(sys.stdout)# create factory protocol and applicationf = LogBotFactory(sys.argv[1], sys.argv[2])# connect factory to this host and portreactor.connectTCP("irc.freenode.net", 6667, f)# run botreactor.run()
運行如下命令:(在連接成功之后,我斷開了網(wǎng)絡(luò)連接測試自動重新連接)
$ python ircLogBot.py test log.logE:\desktop\TwisedLearn\simple_examples>python ircLogBot.py test log.log
2021-04-24 18:02:33+0800 [-] Log opened.
2021-04-24 18:02:33+0800 [-] Starting factory <__main__.LogBotFactory object at 0x000002653455B488>
2021-04-24 18:07:32+0800 [-] connection failed: [Failure instance: Traceback (failure with no frames): <class 'twisted.internet.error.TCPTimedOutError'>: TCP connection timed out: 10060: 由于連接方在一段時間后沒有正確答復(fù)或連接的主機沒有反應(yīng),連接嘗試失敗。.
2021-04-24 18:07:32+0800 [-] ]
2021-04-24 18:07:32+0800 [-] Stopping factory <__main__.LogBotFactory object at 0x000002653455B488>
2021-04-24 18:07:32+0800 [-] Main loop terminated.
對應(yīng)的log.log
:
[18:02:35] [connected at Sat Apr 24 18:02:35 2021]
[18:07:11] [disconnected at Sat Apr 24 18:07:11 2021]