Python websockets库是用于在Python中构建WebSocket服务器和客户端的库。
如果可能,应该使用最新版本的Python。如果使用的是旧版本,请注意,对于每个次要版本(3.x),仅官方支持最新的错误修复版本(3.x.y)。
为了获得最佳体验,应该从Python≥3.6以上版本。asyncio在Python 3.4和3.6之间做了很大的改进。
注意:本文档是为Python≥3.6编写的。
安装websockets
$ pip install websockets
基本的例子
下面是一个WebSocket服务器示例。它从客户端读取名称,发送问候语,然后关闭连接。参考以下实现代码 –
#!/usr/bin/env python # WS server example import asyncio import websockets async def hello(websocket, path): name = await websocket.recv() print(f"< {name}") greeting = f"Hello {name}!" await websocket.send(greeting) print(f"> {greeting}") start_server = websockets.serve(hello, 'localhost', 8765) asyncio.get_event_loop().run_until_complete(start_server) asyncio.get_event_loop().run_forever()
在服务器端,websockets为每个WebSocket连接执行一次处理协同程序hello。它在处理协同程序返回时关闭连接。