国产亚洲精品福利在线无卡一,国产精久久一区二区三区,亚洲精品无码国模,精品久久久久久无码专区不卡

當(dāng)前位置: 首頁 > news >正文

網(wǎng)站建設(shè)新趨勢國內(nèi)新聞大事

網(wǎng)站建設(shè)新趨勢,國內(nèi)新聞大事,做一個網(wǎng)站設(shè)計要多久,大學(xué)生創(chuàng)業(yè)計劃書編寫客戶端程序 twisted 框架是設(shè)計的十分靈活的,他可以讓你編寫強大的客戶端程序。而是現(xiàn)在這種靈活性的代價僅僅是在編寫客戶端程序的時候多添加了幾層。 實際上,你真正實現(xiàn)協(xié)議的解析和處理的是Protocol類。這個類一般是派生自twisted.internet.pro…

編寫客戶端程序

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)建,而不是簡單地傳入hostport,讓函數(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]
http://m.aloenet.com.cn/news/29497.html

相關(guān)文章:

  • 樹形菜單的網(wǎng)站代碼網(wǎng)絡(luò)運營推廣具體做什么工作
  • 做門戶類網(wǎng)站報價上海疫情又要爆發(fā)了
  • 網(wǎng)站服務(wù)器租用有什么好學(xué)大教育一對一收費價格表
  • 郴州企業(yè)網(wǎng)站建設(shè)制作營銷案例100例
  • 網(wǎng)站建站建設(shè)網(wǎng)站中國企業(yè)500強排行榜
  • a0000網(wǎng)站建設(shè)2022年seo最新優(yōu)化策略
  • 博山網(wǎng)站建設(shè)網(wǎng)頁制作基礎(chǔ)教程
  • 四川城鄉(xiāng)住房建設(shè)廳官方網(wǎng)站seo搜索優(yōu)化公司排名
  • 新華社官網(wǎng)百度推廣怎么優(yōu)化
  • 深圳平湖網(wǎng)站建設(shè)有免費推廣平臺
  • 東莞網(wǎng)站推廣優(yōu)化建設(shè)seo站長工具
  • 吳橋縣網(wǎng)站建設(shè)價格沈陽頭條今日頭條新聞最新消息
  • 網(wǎng)站做分站360收錄批量查詢
  • 多少網(wǎng)站域名采用中文四川全網(wǎng)推網(wǎng)絡(luò)推廣
  • 服務(wù)器的做網(wǎng)站空間北京疫情最新新聞
  • 重慶網(wǎng)站建設(shè)最大seo自然排名關(guān)鍵詞來源的優(yōu)缺點
  • 赤峰做網(wǎng)站的公司鄭州seo優(yōu)化顧問熱狗
  • 商城界面設(shè)計武漢seo服務(wù)多少錢
  • 網(wǎng)站改版 域名百度愛企查電話人工服務(wù)總部
  • 武漢網(wǎng)站制作模板小程序推廣方案
  • 怎么做bt爬蟲網(wǎng)站seo專員是什么職位
  • 醫(yī)美三方網(wǎng)站怎么做首頁百度
  • 做軟件跟網(wǎng)站哪個難全國各城市疫情高峰感染進(jìn)度
  • 廈門網(wǎng)站建設(shè)公司推薦windows優(yōu)化大師破解版
  • 發(fā)外鏈的網(wǎng)站都要企業(yè)注冊需要優(yōu)化的地方
  • 做動態(tài)網(wǎng)站怎樣配置iisb2b商務(wù)平臺
  • 專業(yè)網(wǎng)站制作公司教程長尾關(guān)鍵詞什么意思
  • 小白如何免費做網(wǎng)站阿里巴巴國際站關(guān)鍵詞推廣
  • 張家港網(wǎng)站制作哪家好站長資源平臺
  • 如何做網(wǎng)站結(jié)構(gòu)優(yōu)化鄭州粒米seo顧問