多线程websocket代码
时间: 2023-08-27 15:07:08 浏览: 44
下面是一个基于 Python 的多线程 WebSocket 服务器的示例代码:
```python
import asyncio
import websockets
async def handler(websocket, path):
async for message in websocket:
await websocket.send(message)
async def server():
async with websockets.serve(handler, 'localhost', 8765):
await asyncio.Future() # keep server running
async def main():
await asyncio.gather(server())
if __name__ == '__main__':
asyncio.run(main())
```
这个代码使用了 asyncio 和 websockets 库来实现 WebSocket 服务器。`handler` 函数处理每一个 WebSocket 连接,它会将接收到的消息原封不动地返回给客户端。`server` 函数创建 WebSocket 服务器并监听端口 8765。`main` 函数使用 asyncio 来并发运行 `server` 函数。
为了支持多个 WebSocket 连接,可以将 `handler` 函数的实现改为多线程模式,例如:
```python
import asyncio
import threading
import websockets
async def handler(websocket, path):
while True:
message = await websocket.recv()
if message is None:
break
for client in clients:
if client is not websocket:
await client.send(message)
async def serve(websocket, path):
clients.append(websocket)
try:
await handler(websocket, path)
finally:
clients.remove(websocket)
async def server():
async with websockets.serve(serve, 'localhost', 8765):
await asyncio.Future() # keep server running
async def main():
await asyncio.gather(server())
if __name__ == '__main__':
clients = []
asyncio.run(main())
```
这个代码创建了一个全局的 `clients` 列表来保存所有连接的 WebSocket 客户端。在 `handler` 函数中,接收到的消息会被发送给所有客户端(除了发送者本身)。`serve` 函数在客户端连接时将它添加到 `clients` 列表中,并在连接断开时将它从 `clients` 列表中移除。由于 `clients` 列表是一个共享变量,因此需要注意使用线程同步机制来避免并发问题。