我正在尝试使用Python Websockets库构建服务器和客户端。以下是这里给出的示例:Python OCPP文档。我想编辑这个例子,这样对于每个新的客户端(充电桩(,服务器(中央系统(都在新的线程上运行(或者在Websockets库使用Python的asyncio时在新的循环上运行(。基本上,我想同时接收来自多个客户端的消息。我从后面的例子中修改了服务器(中央系统(的主要方法,比如在websockets.serve((中添加一个循环参数,希望每当新客户端运行时,它都会在不同的循环上运行:
async def main():
server = await websockets.serve(
on_connect,
'0.0.0.0',
9000,
subprotocols=['ocpp2.0'],
ssl=ssl_context,
loop=asyncio.new_event_loop(),
ping_timeout=100000000
)
await server.wait_closed()
if __name__ == '__main__':
asyncio.run(main())
我得到以下错误。请帮助:
RuntimeError:
Task <Task pending coro=<main() running at server.py:36>
cb=_run_until_complete_cb() at /usr/lib/python3.7/asyncio/base_events.py:153]>
got Future <_GatheringFuture pending> attached to a different loop - sys:1:
RuntimeWarning: coroutine 'BaseEventLoop._create_server_getaddrinfo' was never awaited
OCPP包的作者。项目中的示例能够通过一个事件循环处理多个客户端。
您的示例中的问题是loop=asyncio.new_event_loop()
。websocket.serve()
是在"main"事件循环中调用的。但您将它传递给第二个事件循环的引用。这导致未来被附加到它创建的不同事件循环。
您应该避免运行多个事件循环。