python实现websocket推送消息
要实现 WebSocket 推送消息,需要使用 Python 的 WebSocket 库,例如 websocket 或 websockets。
以下是使用 websockets 库实现 WebSocket 推送消息的示例代码:
import asyncio
import websockets
async def handler(websocket, path):
while True:
# 接收客户端消息
message = await websocket.recv()
print(f"Received message: {message}")
# 推送消息给所有客户端
for client in clients:
await client.send(message)
async def push_message(message):
# 推送消息给所有客户端
for client in clients:
await client.send(message)
async def main():
# 创建 WebSocket 服务器
async with websockets.serve(handler, "localhost", 8000):
print("WebSocket server started")
while True:
# 周期性推送消息
await asyncio.sleep(1)
await push_message("Hello, world!")
if __name__ == "__main__":
clients = set()
asyncio.run(main())
在上面的示例代码中,handler 函数用于处理客户端连接和消息,push_message 函数用于推送消息给所有客户端,main 函数用于启动 WebSocket 服务器和周期性推送消息。
在客户端连接时,handler 函数会将客户端添加到 clients 集合中,当客户端断开连接时,会自动从集合中移除。
在周期性推送消息时,push_message 函数会遍历 clients 集合,将消息推送给所有客户端。
原文地址: https://www.cveoy.top/t/topic/bczp 著作权归作者所有。请勿转载和采集!