How do I send something to connected websocket clients from another thread?
<p>I am writing a Python 3.5 program which handles some signals and serves this data to a small amount of  websocket clients.
I want the websocket server and the signal handling to happen in the same program, therefore I am using threading.</p>

<p>The problem is I don't know how to send data from the worker thread to the client.</p>

<p>The Websocket server is implemented with a simple library called "websockets". The server is set up and clients can connect and talk to the server within the "new websocket client has connected" handler.</p>

<p>The server is set up with the help of an event loop:</p>

<pre><code>start_server = websockets.serve(newWsHandler, host, port)

loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)
loop.run_forever()
</code></pre>

<p>Because I want my program to do signal handling too, and loop.run_forever() is a blocking call, I create an endless worker thread before I start my server. This works as expected.</p>

<p>When the worker thread detects a signal change, it has to alert the connected websocket clients. But a simple client.send() does not work. Putting await in front of it does not work either (since that only works within coroutines, I think). I tried making a separate "async def" function and adding it to the event loop, but it gets a bit complicated because it's not on the same thread.</p>

<p>So the main question is: what is the best way send something to a websocket client from a worker thread? I don't receive anything in response.</p>

<p>EDIT:
It will probably help if I add some mock code.</p>

<pre><code>def signalHandler():
    #check signals
    ...
    if alert:
        connections[0].send("Alert") #NEED HELP HERE

async def newWsHandler(websocket, path):
    connections.append(websocket)

    while True:
        #keep  the connection open until the client disconnects
        msg = await websocket.recv()

#top level
connections = []
...
start_server = websockets.serve(newWsHandler, host, port)

signalThread = Thread(target = signalHandler)
signalThread.setDaemon(True)
signalThread.start()

loop = asyncio.get_event_loop()
loop.run_until_complete(start_server)

loop.run_forever()
</code></pre>