0

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?

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.