twisted 网络通信的简单例子
生活随笔
收集整理的這篇文章主要介紹了
twisted 网络通信的简单例子
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
2019獨角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>
#!?/usr/bin/env?python #coding=utf-8 from?twisted.internet?import?protocol,?reactor,?defer from?twisted.protocols?import?basic from?gcutils.db?import?MySQLMgr import?sys from?twisted.internet.protocol?import?ServerFactory from?twisted.protocols.basic?import?LineReceiver from?twisted.python?import?log from?twisted.internet?import?reactorclass?CmdProtocol(LineReceiver):delimiter?=?'\n'def?connectionMade(self):self.client_ip?=?self.transport.getPeer().hostlog.msg("Client?connection?from?%s"?%?self.client_ip)if?len(self.factory.clients)?>=?self.factory.clients_max:log.msg("Too?many?connections.?bye?!")self.client_ip?=?Noneself.transport.loseConnection()else:self.factory.clients.append(self.client_ip)def?connectionLost(self,?reason):log.msg('Lost?client?connection.?Reason:?%s'?%?reason)if?self.client_ip:self.factory.clients.remove(self.client_ip)def?lineReceived(self,?line):log.msg('Cmd?received?from?%s?:?%s'?%?(self.client_ip,?line))class?MyFactory(ServerFactory):protocol=CmdProtocoldef?__init__(self,?clients_max=10):self.clients_max?=?clients_maxself.clients?=?[]log.startLogging(sys.stdout) reactor.listenTCP(9999,?MyFactory(2)) reactor.run()在上面的代碼中我們創(chuàng)建了"ServerFactory"類,這個工廠類負(fù)責(zé)返回“CmdProtocol”的實例。每一個連接都由實例化的“CmdProtocol”實例來做處理。?Twisted的reactor會在TCP連接上后自動創(chuàng)建CmdProtocol的實例。如你所見,protocol類的方法都對應(yīng)著一種事件處理。 當(dāng)client連上server之后會觸發(fā)“connectionMade"方法,在這個方法中你可以做一些 鑒權(quán)之類的操作,也可以限制客戶端的連接總數(shù)。每一個protocol的實例都有一個工廠 的引用,使用self.factory可以訪問所在的工廠實例。 上面實現(xiàn)的”CmdProtocol“是twisted.protocols.basic.LineReceiver的子類, LineReceiver類會將客戶端發(fā)送的數(shù)據(jù)按照換行符分隔,每到一個換行符都會觸發(fā) lineReceived方法。稍后我們可以增強LineReceived來解析命令。 Twisted實現(xiàn)了自己的日志系統(tǒng),這里我們配置將日志輸出到stdout 當(dāng)執(zhí)行reactor.listenTCP時我們將工廠綁定到了9999端口開始監(jiān)聽。轉(zhuǎn)載于:https://my.oschina.net/u/1458120/blog/552877
總結(jié)
以上是生活随笔為你收集整理的twisted 网络通信的简单例子的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: hibernate 各种主键生成策略(转
- 下一篇: Windows API(非MFC)编程加