自从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 WebSocketServerProtocol
class 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 verbatim
self.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 sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
from autobahn.twisted.websocket import WebSocketServerFactory
factory = WebSocketServerFactory()
factory.protocol = MyServerProtocol
reactor.listenTCP(9000, factory)
reactor.run()
asyncio 版本
try:
import asyncio
except ImportError:
## Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn.asyncio.websocket import WebSocketServerFactory
factory = WebSocketServerFactory()
factory.protocol = MyServerProtocol
loop = 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:
pass
finally:
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 sys
from twisted.python import log
from twisted.internet import reactor
log.startLogging(sys.stdout)
from autobahn.twisted.websocket import WebSocketClientFactory
factory = WebSocketClientFactory()
factory.protocol = MyClientProtocol
reactor.connectTCP("127.0.0.1", 9000, factory)
reactor.run()
asyncio版本
try:
import asyncio
except ImportError:
## Trollius >= 0.3 was renamed
import trollius as asyncio
from autobahn.asyncio.websocket import WebSocketClientFactory
factory = WebSocketClientFactory()
factory.protocol = MyClientProtocol
loop = 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