我尝试使用asyncio / websockets编写服务器,该服务器在一个端口上侦听单个websocket连接,当它收到消息时,它会将其发送到正在侦听它的所有websockets独立的港口。第二个端口上可能有数百个客户端,所以我知道我需要使用非阻塞await websocket.send(msg)
。但我无法弄清楚如何根据事件循环构建这种倾听/传播范式。
这是我的第一次尝试:
import asyncio
import websockets
import time
LISTEN_PORT = 8080
SPEAK_PORT = 8081
audience = []
async def add_audience_member(websocket, path):
global audience
print('New audience member!')
audience.append(websocket)
async def add_source(websocket, path):
global audience
while True:
msg = await websocket.recv()
for ws in audience:
await ws.send(msg + ' ' + str(time.time()))
loop = asyncio.get_event_loop()
loop.run_until_complete(websockets.serve(add_audience_member, HOST, SPEAK_PORT))
loop.run_until_complete(websockets.serve(add_source, HOST, LISTEN_PORT))
loop.run_forever()
然后我有一个客户端正在运行:
from websocket import create_connection
ws = create_connection('ws://{}:{}'.format(HOST, 8081))
while True:
data = ws.recv(); print data
问题是add_audience_member在将新的websocket添加到受众列表后立即关闭连接,因此我收到错误:
websocket._exceptions.WebSocketConnectionClosedException: Connection is already closed.