python websockets 多客户端
时间: 2023-09-15 13:16:38 浏览: 44
要实现Python WebSockets多客户端,你需要使用一个WebSocket服务端,比如 `websockets` 库。下面是一个简单的例子:
```python
import asyncio
import websockets
async def handler(websocket, path):
async for message in websocket:
print(f'Received message: {message}')
await websocket.send(f'Response to {message}')
async def main():
async with websockets.serve(handler, 'localhost', 8765):
print('WebSocket server started.')
await asyncio.Future() # keep the server running
if __name__ == '__main__':
asyncio.run(main())
```
这个简单的WebSocket服务端会监听 `localhost` 的 `8765` 端口,接收来自客户端的消息并返回响应。
如果你想让它能够同时处理多个客户端,只需要在handler中使用asyncio.gather()即可:
```python
import asyncio
import websockets
async def handler(websocket, path):
async for message in websocket:
print(f'Received message: {message}')
tasks = [websocket.send(f'Response to {message} from client {i}') for i in range(5)]
await asyncio.gather(*tasks)
async def main():
async with websockets.serve(handler, 'localhost', 8765):
print('WebSocket server started.')
await asyncio.Future() # keep the server running
if __name__ == '__main__':
asyncio.run(main())
```
这样,当有客户端连接时,服务端会同时向其它5个客户端发送消息。你可以根据实际需求进行调整。