Twisted 介绍 及TCP广播系统实例
twisted 提供更多傳輸層 udp,tcp,tls及應用層HTTP,FTP等協議的支持,在開發方法上更提供了豐富的特性來支持異步編程
安裝twisted
建議使用anaconda 安裝,conda install twisted,
Windows 安裝需要先安裝兩個支持庫,zope inteeface和pywin32 然后pip?install twisted,
Linux系統 直接命令行 apt-get install python-twisted 或者yum install?python-twisted?
實戰演練 - 開發TCP廣播系統
系統描述:廣播系統接收任意客戶端的鏈接請求,并將任意客戶端發送給服務器的消息轉發給所有其他客戶端,本系統是一個基本的實時通信模型
1、廣播服務器
?twisted基于傳輸層TCP編程時,直接針對Twisted的Protocol,Factory等類進行編程,而無需操作socket里面的bind,send,receive等基本用語,并且定義他們的子類并重寫connectionMode,dataReceived進行事件化的TCP變成風格
- connectionMode() 當鏈接建立時由twisted框架調用,本函數主要作用是在系統中注冊該鏈接,方便調用
- dataReceived() 當收到客戶端數據時由twisted框架調用
- connectionLost()當鏈接斷開時由框架調用,實際應用中用來清理鏈接占用的資源?
本廣播系統的Protocol代碼為:
from twisted.internet.protocol import Protocolclients = [] # 保存所有客戶端連接class Spreader (Protocol): # 繼承Protocol,實現需要重載的方法def __init__(self, factory):self.factory = factorydef connectionMade(self): # 對連接的客戶端計數,并保存到clients列表中self.factory.numProtocols = self.factory.numProtocols + 1self.transport.write (("歡迎來到Spread site,你是第%d 個客戶端用戶!\n" % (self.factory.numProtocols)).encode ('utf8'))print ("新連接: %d" % self.factory.numProtocols)clients.append (self)def connectionLost(self, reason): # 執行反向操作self.factory.numProtocols = self.factory.numProtocols - 1clients.remove (self)print ("關閉連接:%d" % self.factory.numProtocols)def dataReceived(self, data): # 循環當前clients列表中的所有客戶端,將受到的數據,分發給自己之外的所有客戶端if data == 'close': # 如果受到客戶端發來的數據‘close’ ,則主動關閉與該客戶端的鏈接 self.transport.lostConnection ()for client in clients:if client != self:client.transport.write (data)開發Factory子類
Factory類起到了 對Protocol 類的管理作用,當有新的客戶端鏈接時,框架調用Factory.buildProtocol(),可以創建Protoco子類的實例,代碼如下
from twisted.internet.protocol import Factoryfrom twisted.internet.endpoints import TCP4ServerEndpoint from twisted.internet import reactorclass SpreaderFactory(Factory):def __init__(self):self.numProtocols = 0def buildProtocol(self, addr):return Spreader(self)# 8007是本服務器的監聽端口 endpoint = TCP4ServerEndpoint(reactor,8007) endpoint.listen(SpreaderFactory())reactor.run() # 掛起運行2、廣播客戶端
實現與服務器程序相匹配的TCP客戶端程序
from twisted.internet.protocol import Protocol, ClientFactoryfrom twisted.internet import reactor import threading import fileinput import time import sys import datetimeclass Echo (Protocol): # Protocol子類,此處進行通信邏輯開發def __init__(self):self.connected = False # 在函數routine中使用該狀態決定是否向服務器發送消息def connectionMade(self):self.connected = Truedef connectionLost(self, reason):self.connected = Falsedef dataReceived(self, data):print (data.decode ('utf8'))class EchoClientFactory (ClientFactory): # Factory子類,管理鏈接關系def __init__(self):self.protocol = Nonedef startedConnecting(self, connector):print ("開始鏈接")def buildProtocol(self, addr):print ('已連接')self.protocol = Echo ()return self.protocoldef clientConnectionLost(self, connector, reason):print ("鏈接丟失,原因是:", reason)def clientConnectionFailed(self, connector, reason):print ('鏈接失敗,原因是:', reason)bStop = Falsedef routine(factory): # 每隔5秒向服務器發送消息while not bStop:if factory.protocol and factory.protocol.connected:factory.protocol.transport.write(('hello,i am xx %s' % (datetime.datetime.now())).encode('utf8'))time.sleep(5)host = '127.0.0.1' port = 8007 factory = EchoClientFactory() reactor.connectTCP(host,port,factory) threading.Thread(target=routine,args=(factory,)).start() # 啟動縣城運行routine()函數 reactor.run() # 掛起運行 bStop = True # 通知routine線程退出?結果:
server:
?
客戶端:
?
轉載于:https://www.cnblogs.com/Erick-L/p/7084810.html
總結
以上是生活随笔為你收集整理的Twisted 介绍 及TCP广播系统实例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Linux 下crontab简单使用
- 下一篇: 将redis作为windows服务安装