Skip to content Skip to sidebar Skip to footer

Starting Websocket Server In Different Thread/event Loop

I'm building a Websocket server application in python 3. I'm using this implementation: https://websockets.readthedocs.io/ Basically I want to launch the server and client in the s

Solution 1:

The problem is that you have started your background thread first, and then attempted to make use of it (instead, as general principle, setup your objects first, and then start the thread). Another problem is that you are not calling run_until_complete as in the example.

So to fix:

(1) fix the start_loop function according to the websockets example, so code becomes

def start_loop(loop, server):
    loop.run_until_complete(server)
    loop.run_forever()

(2) set up your server object before starting the background thread:

new_loop = asyncio.new_event_loop()
start_server = websockets.serve(hello, server_host, server_port, loop=new_loop)
t = Thread(target=start_loop, args=(new_loop, start_server))
t.start()

Finally, before trying to connect to the server, sleep a short while to allow the server to have started listening (ideally you would have a better synchronisation mechanism for this, but a brief sleep will work most of the time):

print("Server launched")
# give sometimefor server tostart, before we try toconnect
time.sleep(2)

Post a Comment for "Starting Websocket Server In Different Thread/event Loop"