python webscoket(Autobahn)的使用
自從18年4月份入職游戲公司之后很少有時間寫博客了!
今天來聊聊python的websocket的使用,在游戲行業游戲客戶端和服務端需要大量的,快速的通訊,這里面就會用到websocket
Autobahn 是一個高性能的websocket 它采用了兩種實現方案
1 基于Twisted
2 基于asyncio
Autobahn 有如下的特點:
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 (可以運行在Cpython, PyPy 和Jython 上面)
runs under Twisted and asyncio (可以選擇Twisted 或者是asyncio的方式來運行)
implements WebSocket RFC6455 (and draft versions Hybi-10+) (實現WebSocket RFC6455(以及草案版本Hybi-10 +))
implements WebSocket compression (實現WebSocket壓縮)
implements WAMP, the Web Application Messaging Protocol (實現Web應用程序消息傳遞協議)
supports TLS (secure WebSocket) and proxies (支持TLS(安全WebSocket)和代理)
Open-source (MIT license) (開源)
Autobahn 可以用來做什么
Autobahn 非常適用于交易系統,多人游戲, 實時聊天等應用程序的開發
一個簡單的webSocket服務端程序
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))幾個重要的方法:
onConnect: 當有新的客戶端連接進來的時候調用該方法
onOpen: 當連接成功時調用該方法
onMessage: 該方法是接收來自客戶端的消息
onClose: 當關閉時調用該方法
安裝Autobahn
Autobahn 的運行依賴于 Twisted 和 asyncio 因此安裝Autobahn 需要確認你的python支持了
Twisted 和 asyncio
各個python 版本對 Twisted 和 asyncio 支持如下
使用pip 安裝
pip install autobahn[twisted]
pip install autobahn[asyncio]
驗證是否安裝成功
from autobahn import version
print(version)
0.9.1
啟動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()創建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()發送消息
當我們的server或者client 繼承了autobahn之后就可以使用 sendMessage 方法來發送消息
接收消息
當我們的server或者client 實現了onMessage(self, payload, isBinary): 定義了該方法之后,就可以接收到消息
更多詳細介紹請查看: https://autobahn.readthedocs.io/en/latest/index.html
總結
以上是生活随笔為你收集整理的python webscoket(Autobahn)的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: linux查看优盘端口,ubuntu中查
- 下一篇: 手把手教你学习FPGA系列视频教程_救护