简体   繁体   中英

Multithreaded server using Python Websockets library

I am trying to build a Server and Client using Python Websockets library. I am following the example given here: Python OCPP documentation . I want to edit this example such that for each new client(Charge Point), the server(Central System) runs on new thread (or new loop as Websockets library uses Python's asyncio). Basically I want to receive messages from multiple clients simultaneously. I modified the main method of server(Central System), from the example that I followed, like this by adding a loop parameter in websockets.serve() in a hope that whenever a new client runs, it runs on a different loop:

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())

I am getting the following error. Please help:

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

Author of the OCPP package here. The examples in the project are able to handle multiple clients with 1 event loop.

The problem in your example is loop=asyncio.new_event_loop() . The websocket.serve() is called in the 'main' event loop. But you pass it a reference to a second event loop. This causes the future to be attached to a different event loop it was created it.

You should avoid running multiple event loops.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM