bird12358
bird12358

Reputation: 109

Python websocket in a thread

I try to run a websocket in python in a thread. Here is the example I made:

import asyncio
import websockets
import threading
class websocket(threading.Thread):
    def run(self):

        asyncio.get_event_loop().run_until_complete(
            websockets.serve(self.echo, 'localhost', 8765))
        asyncio.get_event_loop().run_forever()

    async def echo(websocket, path):
        async for message in websocket:
            await websocket.send(message)


ws = websocket()

ws.start()

I get that error:

Exception in thread Thread-1:
Traceback (most recent call last):
  File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner
    self.run()
  File "/home/xavier/dev/3003_mdt/mdt-robotarm/robotarm_server.py", line 7, in run
    asyncio.get_event_loop().run_until_complete(
  File "/usr/lib/python3.6/asyncio/events.py", line 694, in get_event_loop
    return get_event_loop_policy().get_event_loop()
  File "/usr/lib/python3.6/asyncio/events.py", line 602, in get_event_loop
    % threading.current_thread().name)
RuntimeError: There is no current event loop in thread 'Thread-1'.


Process finished with exit code 0

How can I run the websocket in a thread?

Upvotes: 0

Views: 817

Answers (1)

frost-nzcr4
frost-nzcr4

Reputation: 1620

You've got the error because get_event_loop creates the loop automatically only in the main thread. Create the loop manually with new_event_loop like this:

loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(
    websockets.serve(self.echo, "localhost", 8765)
)
loop.close()

Upvotes: 1

Related Questions