【发布时间】:2021-04-30 01:58:05
【问题描述】:
我是 websockets 和 asyncio 的新手,我正在尝试让一个简单的示例正常工作。我想创建一个接受来自多个客户端的连接并同时运行一个循环的服务器,该循环每秒向每个连接发送一次消息。我也在尝试使用 asyncio.run(),我认为它优于许多示例所基于的 get_event_loop() 代码。
到目前为止,这是我的代码:
import asyncio
import websockets
USERS = set()
async def register(websocket, path):
USERS.add(websocket)
await websocket.send("Successfully registered")
async def count():
count = 0
while True:
print(f"Iteration: {count}")
if USERS:
for user in USERS:
await user.send("Sending message back to client")
await asyncio.sleep(1)
count +=1
async def serve():
server = await websockets.serve(register, 'localhost', 8765)
await server.wait_closed()
print("Server closed")
async def main():
await asyncio.gather(count(), serve())
asyncio.run(main())
当我运行它时,计数协程会一直工作,直到我从客户端建立连接。此时连接已成功注册,但是当我尝试在 count() 中将消息发送回客户端时,由于连接已关闭,我收到错误消息。我应该如何更改我的代码以阻止这种情况发生?
【问题讨论】:
标签: python websocket python-asyncio