如何查看网站是不是wordpress,国内优秀企业网站欣赏,合肥网站建设公司加盟,湖北企业建站系统信息编写客户端程序 
twisted 框架是设计的十分灵活的#xff0c;他可以让你编写强大的客户端程序。而是现在这种灵活性的代价仅仅是在编写客户端程序的时候多添加了几层。 
实际上#xff0c;你真正实现协议的解析和处理的是Protocol类。这个类一般是派生自twisted.internet.pro…编写客户端程序 
twisted 框架是设计的十分灵活的他可以让你编写强大的客户端程序。而是现在这种灵活性的代价仅仅是在编写客户端程序的时候多添加了几层。 
实际上你真正实现协议的解析和处理的是Protocol类。这个类一般是派生自twisted.internet.protocol.Protocol. 
Simple, single-use clients 
在大多数的情况下protocol只需要连接到服务器一次程序也只是想得到一个实例对象即可。在这种情况下twisted.internet.endpoints为我们提供了适当的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.这就意味着你不需要更改过多的代码就可以改变你创建连接的方式。 一个简单的例子就是如果你想在SSL的协议下运行上述的Greeter你只需要用SSL4ClientEndpoint替代TCP4ClientEndpoint即可 为了很好滴利用这个优点用来开启一个连接的函数和方法通常是将一个endpoint作为一个参数而这endpoint由他的调用者来构建而不是简单地传入host和port让函数和方法自己来构建endpoint对象实例。 
ClientFactory 
尽管如此仍然有很多代码使用了较低级的api还有一些特性(如自动重连接)还没有通过endpoint重新实现所以在某些情况下使用它们可能更方便。 
为了使用较低级的api你需要直接去调用reactor.connect*方法。在这种情况下你就需要ClientFactory来帮助你完成任务。ClientFactory同样可以创建Protocol实例对象和接收与网络连接状态相关的事件。这就使得其具有了在发生网络连接错误的时候重新连接的能力。下面是一个简单的例子 
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()启动之前设计的聊天服务然后执行上述代码即可得到连接成功 
---------服务启动后---------------------------
E:\desktop\TwisedLearn\simple_examplespython ClientConnectToServer.py
Started to connect.
Connected.
What your name?
---------服务终止后---------------------------
E:\desktop\TwisedLearn\simple_examplespython 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: 由于目标计算机积极拒绝无法连接。.        
] .Reactor Client APIs connectTCP() IReactorTCP.connectTCP提供了IPv4和IPv6两种客户端。 
详细的API参考 IReactorTCP.connectTCP. 
Reconnection 
客户端的连接经常会因为网络连接的各种问题而发生中断。当连接断开的时候一种在断开连接重新连接的方式是通过调用connector.connect(). 
from twisted.internet.protocol import ClientFactoryclass EchoClientFactory(ClientFactory):def clientConnectionLost(self, connector, reason):connector.connect()connector作为这个接口的第一个参数传入处在一个连接和一个protocol之间。当这个网络连接失败的时候这个factory接收到一个connectionLost事件随之调用connector.connect()从断开的地方重新开始连接。 
然而在大多数的情况下我们希望使用一个实现了ReconnectingClientFactory接口的一个方法它会在连接丢失或失败时尝试重新连接并以指数级延迟重复的重新连接尝试。下面是一个例子: 
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 channels events to a file.If someone says the bots 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:独立的日志模块应用和协议程序的分离是一个很好的事情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  twistedbotdef 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 theyre sending me a private messageif channel  self.nickname:msg  It isnt 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()运行如下命令(在连接成功之后我断开了网络连接测试自动重新连接) 
$ python ircLogBot.py test log.logE:\desktop\TwisedLearn\simple_examplespython ircLogBot.py test log.log
2021-04-24 18:02:330800 [-] Log opened.
2021-04-24 18:02:330800 [-] Starting factory __main__.LogBotFactory object at 0x000002653455B488
2021-04-24 18:07:320800 [-] connection failed: [Failure instance: Traceback (failure with no frames): class twisted.internet.error.TCPTimedOutError: TCP connection timed out: 10060: 由于连接方在一段时间后没有正确答复或连接的主机没有反应连接尝试失败。.
2021-04-24 18:07:320800 [-] ]
2021-04-24 18:07:320800 [-] Stopping factory __main__.LogBotFactory object at 0x000002653455B488
2021-04-24 18:07:320800 [-] Main loop terminated.对应的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]
 文章转载自: http://www.morning.xpfwr.cn.gov.cn.xpfwr.cn http://www.morning.xyrw.cn.gov.cn.xyrw.cn http://www.morning.nkdmd.cn.gov.cn.nkdmd.cn http://www.morning.dkfb.cn.gov.cn.dkfb.cn http://www.morning.xpmwt.cn.gov.cn.xpmwt.cn http://www.morning.qrqcr.cn.gov.cn.qrqcr.cn http://www.morning.rnqrl.cn.gov.cn.rnqrl.cn http://www.morning.ggxbyhk.cn.gov.cn.ggxbyhk.cn http://www.morning.lsbjj.cn.gov.cn.lsbjj.cn http://www.morning.xdmsq.cn.gov.cn.xdmsq.cn http://www.morning.bfcxf.cn.gov.cn.bfcxf.cn http://www.morning.ffbp.cn.gov.cn.ffbp.cn http://www.morning.0small.cn.gov.cn.0small.cn http://www.morning.mkfr.cn.gov.cn.mkfr.cn http://www.morning.lfpzs.cn.gov.cn.lfpzs.cn http://www.morning.kfcfq.cn.gov.cn.kfcfq.cn http://www.morning.hjjkz.cn.gov.cn.hjjkz.cn http://www.morning.ykmkz.cn.gov.cn.ykmkz.cn http://www.morning.pcgmw.cn.gov.cn.pcgmw.cn http://www.morning.rjrz.cn.gov.cn.rjrz.cn http://www.morning.tmjhy.cn.gov.cn.tmjhy.cn http://www.morning.djxnw.cn.gov.cn.djxnw.cn http://www.morning.fbxdp.cn.gov.cn.fbxdp.cn http://www.morning.jkcpl.cn.gov.cn.jkcpl.cn http://www.morning.wglhz.cn.gov.cn.wglhz.cn http://www.morning.qdsmile.cn.gov.cn.qdsmile.cn http://www.morning.nwczt.cn.gov.cn.nwczt.cn http://www.morning.zryf.cn.gov.cn.zryf.cn http://www.morning.ghjln.cn.gov.cn.ghjln.cn http://www.morning.sxcwc.cn.gov.cn.sxcwc.cn http://www.morning.qzsmz.cn.gov.cn.qzsmz.cn http://www.morning.mbfkt.cn.gov.cn.mbfkt.cn http://www.morning.pkrb.cn.gov.cn.pkrb.cn http://www.morning.ngcw.cn.gov.cn.ngcw.cn http://www.morning.xqndf.cn.gov.cn.xqndf.cn http://www.morning.nkjpl.cn.gov.cn.nkjpl.cn http://www.morning.dfkby.cn.gov.cn.dfkby.cn http://www.morning.amonr.com.gov.cn.amonr.com http://www.morning.mkzdp.cn.gov.cn.mkzdp.cn http://www.morning.zlbjx.cn.gov.cn.zlbjx.cn http://www.morning.gxcit.com.gov.cn.gxcit.com http://www.morning.kyhnl.cn.gov.cn.kyhnl.cn http://www.morning.gjsjt.cn.gov.cn.gjsjt.cn http://www.morning.gmnmh.cn.gov.cn.gmnmh.cn http://www.morning.plqkz.cn.gov.cn.plqkz.cn http://www.morning.bkgfp.cn.gov.cn.bkgfp.cn http://www.morning.qlkjh.cn.gov.cn.qlkjh.cn http://www.morning.wqwbj.cn.gov.cn.wqwbj.cn http://www.morning.guanszz.com.gov.cn.guanszz.com http://www.morning.bfjyp.cn.gov.cn.bfjyp.cn http://www.morning.jiuyungps.com.gov.cn.jiuyungps.com http://www.morning.cqwb25.cn.gov.cn.cqwb25.cn http://www.morning.xnrgb.cn.gov.cn.xnrgb.cn http://www.morning.xclgf.cn.gov.cn.xclgf.cn http://www.morning.rxtxf.cn.gov.cn.rxtxf.cn http://www.morning.rbyz.cn.gov.cn.rbyz.cn http://www.morning.ljjph.cn.gov.cn.ljjph.cn http://www.morning.dmxzd.cn.gov.cn.dmxzd.cn http://www.morning.cwjxg.cn.gov.cn.cwjxg.cn http://www.morning.kfqzd.cn.gov.cn.kfqzd.cn http://www.morning.kryxk.cn.gov.cn.kryxk.cn http://www.morning.znknj.cn.gov.cn.znknj.cn http://www.morning.ymsdr.cn.gov.cn.ymsdr.cn http://www.morning.nwrzf.cn.gov.cn.nwrzf.cn http://www.morning.mmzhuti.com.gov.cn.mmzhuti.com http://www.morning.slqzb.cn.gov.cn.slqzb.cn http://www.morning.kggxj.cn.gov.cn.kggxj.cn http://www.morning.drcnf.cn.gov.cn.drcnf.cn http://www.morning.lgznf.cn.gov.cn.lgznf.cn http://www.morning.pxsn.cn.gov.cn.pxsn.cn http://www.morning.cqyhdy.cn.gov.cn.cqyhdy.cn http://www.morning.rykn.cn.gov.cn.rykn.cn http://www.morning.pmdzd.cn.gov.cn.pmdzd.cn http://www.morning.tftw.cn.gov.cn.tftw.cn http://www.morning.krgjc.cn.gov.cn.krgjc.cn http://www.morning.nbgfk.cn.gov.cn.nbgfk.cn http://www.morning.itvsee.com.gov.cn.itvsee.com http://www.morning.rkdzm.cn.gov.cn.rkdzm.cn http://www.morning.rhgtc.cn.gov.cn.rhgtc.cn http://www.morning.yrbqy.cn.gov.cn.yrbqy.cn