python webscoket(Autobahn)的使用
自從18年4月份入職游戲公司之后很少有時(shí)間寫博客了!
今天來(lái)聊聊python的websocket的使用,在游戲行業(yè)游戲客戶端和服務(wù)端需要大量的,快速的通訊,這里面就會(huì)用到websocket
Autobahn 是一個(gè)高性能的websocket 它采用了兩種實(shí)現(xiàn)方案
1 基于Twisted
2 基于asyncio
Autobahn 有如下的特點(diǎn):
framework for WebSocket and WAMP clients (Websocket框架和WAMP框架)
compatible with Python 2.7 and 3.3+ (兼容python2.7和python3.3以上的版本)
runs on CPython, PyPy and Jython (可以運(yùn)行在Cpython, PyPy 和Jython 上面)
runs under Twisted and asyncio (可以選擇Twisted 或者是asyncio的方式來(lái)運(yùn)行)
implements WebSocket RFC6455 (and draft versions Hybi-10+) (實(shí)現(xiàn)WebSocket RFC6455(以及草案版本Hybi-10 +))
implements WebSocket compression (實(shí)現(xiàn)WebSocket壓縮)
implements WAMP, the Web Application Messaging Protocol (實(shí)現(xiàn)Web應(yīng)用程序消息傳遞協(xié)議)
supports TLS (secure WebSocket) and proxies (支持TLS(安全WebSocket)和代理)
Open-source (MIT license) (開(kāi)源)
Autobahn 可以用來(lái)做什么
Autobahn 非常適用于交易系統(tǒng),多人游戲, 實(shí)時(shí)聊天等應(yīng)用程序的開(kāi)發(fā)
一個(gè)簡(jiǎn)單的webSocket服務(wù)端程序
from autobahn.twisted.websocket import WebSocketServerProtocol # or: from autobahn.asyncio.websocket import WebSocketServerProtocolclass MyServerProtocol(WebSocketServerProtocol):def onConnect(self, request):print("Client connecting: {}".format(request.peer))def onOpen(self):print("WebSocket connection open.")def onMessage(self, payload, isBinary):if isBinary:print("Binary message received: {} bytes".format(len(payload)))else:print("Text message received: {}".format(payload.decode('utf8')))## echo back message verbatimself.sendMessage(payload, isBinary)def onClose(self, wasClean, code, reason):print("WebSocket connection closed: {}".format(reason))幾個(gè)重要的方法:
onConnect: 當(dāng)有新的客戶端連接進(jìn)來(lái)的時(shí)候調(diào)用該方法
onOpen: 當(dāng)連接成功時(shí)調(diào)用該方法
onMessage: 該方法是接收來(lái)自客戶端的消息
onClose: 當(dāng)關(guān)閉時(shí)調(diào)用該方法
安裝Autobahn
Autobahn 的運(yùn)行依賴于 Twisted 和 asyncio 因此安裝Autobahn 需要確認(rèn)你的python支持了
Twisted 和 asyncio
各個(gè)python 版本對(duì) Twisted 和 asyncio 支持如下
使用pip 安裝
pip install autobahn[twisted]
pip install autobahn[asyncio]
驗(yàn)證是否安裝成功
from autobahn import version
print(version)
0.9.1
啟動(dòng)webScoketServer
twisted 版本
import sysfrom twisted.python import logfrom twisted.internet import reactorlog.startLogging(sys.stdout)from autobahn.twisted.websocket import WebSocketServerFactoryfactory = WebSocketServerFactory()factory.protocol = MyServerProtocolreactor.listenTCP(9000, factory)reactor.run()asyncio 版本
try:import asyncioexcept ImportError:## Trollius >= 0.3 was renamedimport trollius as asynciofrom autobahn.asyncio.websocket import WebSocketServerFactoryfactory = WebSocketServerFactory()factory.protocol = MyServerProtocolloop = asyncio.get_event_loop()coro = loop.create_server(factory, '127.0.0.1', 9000)server = loop.run_until_complete(coro)try:loop.run_forever()except KeyboardInterrupt:passfinally:server.close()loop.close()創(chuàng)建WebSocketClient
class MyClientProtocol(WebSocketClientProtocol):def onOpen(self):self.sendMessage(u"Hello, world!".encode('utf8'))def onMessage(self, payload, isBinary):if isBinary:print("Binary message received: {0} bytes".format(len(payload)))else:print("Text message received: {0}".format(payload.decode('utf8')))WebSocketClientProtocol 可以使用:
autobahn.twisted.websocket.WebSocketClientProtocol
autobahn.asyncio.websocket.WebSocketClientProtocol
使用Client
Twisted版本
import sysfrom twisted.python import logfrom twisted.internet import reactorlog.startLogging(sys.stdout)from autobahn.twisted.websocket import WebSocketClientFactoryfactory = WebSocketClientFactory()factory.protocol = MyClientProtocolreactor.connectTCP("127.0.0.1", 9000, factory)reactor.run()asyncio版本
try:import asyncioexcept ImportError:## Trollius >= 0.3 was renamedimport trollius as asynciofrom autobahn.asyncio.websocket import WebSocketClientFactoryfactory = WebSocketClientFactory()factory.protocol = MyClientProtocolloop = asyncio.get_event_loop()coro = loop.create_connection(factory, '127.0.0.1', 9000)loop.run_until_complete(coro)loop.run_forever()loop.close()發(fā)送消息
當(dāng)我們的server或者client 繼承了autobahn之后就可以使用 sendMessage 方法來(lái)發(fā)送消息
接收消息
當(dāng)我們的server或者client 實(shí)現(xiàn)了onMessage(self, payload, isBinary): 定義了該方法之后,就可以接收到消息
更多詳細(xì)介紹請(qǐng)查看: https://autobahn.readthedocs.io/en/latest/index.html
總結(jié)
以上是生活随笔為你收集整理的python webscoket(Autobahn)的使用的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux查看优盘端口,ubuntu中查
- 下一篇: python socket自动重连_py