使用python的websockets库构建websocket服务是高效且直观的方案,1. 因其基于asyncio,天然支持高并发异步i/o,每个连接由独立协程处理,通过async for循环接收消息,利用asyncio.gather实现高效广播;2. 服务器通过websockets.serve启动,客户端用websockets.connect连接,代码简洁清晰;3. 常见问题如死连接可通过设置ping_interval和ping_timeout启用心跳机制解决;4. 错误处理需捕获connectionclosed异常并在finally中清理连接;5. 安全性方面应使用wss加密通信并校验origin头防止跨站劫持;6. 优化策略包括采用protobuf等高效序列化格式、避免阻塞操作、结合redis pub/sub实现分布式消息同步,最终构建稳定、可扩展的websocket服务。

Python构建WebSocket服务,用
websockets
asyncio
要构建一个基本的WebSocket服务,你需要一个服务器端和一个客户端。服务器端通常使用
websockets
serve
服务器端示例 (server.py
立即学习“Python免费学习笔记(深入)”;
import asyncio
import websockets
import json # 假设我们可能需要处理JSON数据
# 维护所有连接的客户端,用于广播或其他管理
connected_clients = set()
async def handler(websocket, path):
"""
处理每个新的WebSocket连接。
`websocket` 是当前连接的实例。
`path` 是客户端请求的URL路径(通常不怎么用,除非你根据路径区分服务)。
"""
print(f"客户端 {websocket.remote_address} 已连接。")
connected_clients.add(websocket) # 将新连接加入集合
try:
async for message in websocket:
# 收到消息,可以做一些处理,比如解析JSON
print(f"收到来自 {websocket.remote_address} 的消息: {message}")
try:
data = json.loads(message)
if data.get("type") == "broadcast":
response_message = f"广播消息: {data.get('content', '无内容')}"
# 广播给所有在线客户端
await asyncio.gather(*[client.send(response_message) for client in connected_clients if client != websocket])
else:
await websocket.send(f"服务器回应: {message}") # 回复给发送者
except json.JSONDecodeError:
await websocket.send(f"服务器回应 (非JSON): {message}")
except websockets.exceptions.ConnectionClosedOK:
print(f"客户端 {websocket.remote_address} 正常关闭连接。")
except websockets.exceptions.ConnectionClosedError as e:
print(f"客户端 {websocket.remote_address} 连接异常关闭: {e}")
finally:
connected_clients.remove(websocket) # 移除断开的连接
print(f"客户端 {websocket.remote_address} 已断开。")
async def main():
# 启动WebSocket服务器
# `websockets.serve` 是一个异步上下文管理器
async with websockets.serve(handler, "localhost", 8765):
print("WebSocket服务器已启动,监听 ws://localhost:8765")
await asyncio.Future() # 保持服务器运行直到被手动停止
if __name__ == "__main__":
asyncio.run(main())
客户端示例 (client.py
import asyncio
import websockets
import json
async def send_message():
uri = "ws://localhost:8765"
async with websockets.connect(uri) as websocket:
print("已连接到服务器。")
# 发送一条普通消息
await websocket.send("Hello from client!")
response = await websocket.recv()
print(f"收到服务器回应: {response}")
# 发送一条广播消息
broadcast_data = {"type": "broadcast", "content": "大家注意,这是一条广播!"}
await websocket.send(json.dumps(broadcast_data))
# 广播消息通常不会有直接回复,除非服务器特意发送
# 保持连接,等待其他广播消息
print("等待其他客户端的广播消息 (按 Ctrl+C 退出)...")
try:
while True:
incoming_message = await websocket.recv()
print(f"收到广播: {incoming_message}")
except asyncio.CancelledError:
print("客户端已关闭。")
except websockets.exceptions.ConnectionClosedOK:
print("服务器已关闭连接。")
if __name__ == "__main__":
asyncio.run(send_message())
运行步骤:
python server.py
python client.py
websockets
在Python的异步生态里,
websockets
asyncio
asyncio
websockets
它抽象掉了WebSocket协议的各种底层细节,比如握手、帧的打包与解包、心跳维持等等。这意味着开发者可以把精力完全放在业务逻辑上,而不是被协议的实现细节所困扰。我记得早期尝试用Python做一些TCP层面的通信时,光是协议解析就让人头大,更别提WebSocket这种更复杂的了。有了
websockets
另外,它对RFC 6455(WebSocket协议标准)的遵循度很高,这保证了你构建的服务能与各种主流的WebSocket客户端(浏览器、移动应用、其他编程语言的客户端)良好兼容。一个符合标准的库,总是能让人用得更安心。而且,社区活跃,遇到问题也比较容易找到解决方案或者得到帮助,这在实际项目中是相当重要的。
处理并发连接和消息是WebSocket服务的核心挑战之一,但
websockets
asyncio
async/await
每个新的WebSocket连接,在
websockets
websockets.serve
handler
await websocket.recv()
至于消息处理,通常的做法是在
handler
async for message in websocket:
await websocket.send(message)
connected_clients
await client.send(message)
这里有个小技巧:当需要同时向多个客户端发送消息时,使用
asyncio.gather(*[client.send(...) for client in connected_clients])
在实际部署和运行WebSocket服务时,确实会遇到一些问题,也有不少可以优化的点。
一个很常见的问题是“死连接”。客户端可能在没有正常关闭连接的情况下断开(比如网络突然中断、浏览器崩溃),服务器端并不会立即知道。这时,你的
connected_clients
websockets
serve
ping_interval
ping_timeout
ping_interval=20
ping_timeout
另一个是错误处理。网络通信总是充满不确定性。客户端连接可能突然中断,发送的数据格式可能不符合预期。在
handler
try...except websockets.exceptions.ConnectionClosedOK
websockets.exceptions.ConnectionClosedError
finally
connected_clients
try...except
安全性也是不可忽视的一环。首先,生产环境务必使用WSS (WebSocket Secure),即基于TLS/SSL的WebSocket。这和HTTPS是类似的,可以加密通信内容,防止中间人攻击。在
websockets.serve
ssl_context
Origin
handler
websocket.request_headers['Origin']
最后,关于性能优化,除了上面提到的并发处理,如果你预期有海量的连接或消息吞吐,可以考虑:
handler
asyncio.to_thread()
以上就是Python如何构建WebSocket服务?websockets库的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号