python websocket库和websockets
时间: 2024-11-13 21:12:19 浏览: 23
Python 的 `websockets` 库是一个轻量级的、纯 Python 实现的 WebSocket 服务器客户端库。WebSocket 是一种在单个 TCP 连接上进行全双工通信的协议,使得浏览器能够与服务器进行实时双向数据交换,常用于实现实时应用,比如聊天应用、在线游戏等。
`websockets` 提供了简单易用的 API,让你能快速构建 WebSockets 服务和客户端。它支持自动处理连接、心跳检测、断线重连等功能,并且兼容 Python 3.x。安装这个库通常通过 pip 完成:
```bash
pip install websockets
```
使用示例(服务器端):
```python
import asyncio
from websockets import serve
async def handle_connection(websocket, path):
async for message in websocket:
print(f"Received: {message}")
await websocket.send(message)
start_server = await serve(handle_connection, "localhost", 8765)
print("Server started at ws://localhost:8765")
await start_server.wait_closed()
```
客户端示例:
```python
import websockets
async def connect():
async with websockets.connect('ws://localhost:8765') as websocket:
greeting = await websocket.recv()
await websocket.send(greeting + '!')
print(f"Sent: {greeting}!")
asyncio.get_event_loop().run_until_complete(connect())
```
阅读全文