Python 线程中的 websocket

Python websocket in a thread

我尝试在线程中 运行 python 中的 websocket。这是我做的例子:

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

我收到那个错误:

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

如何运行线程中的websocket?

您遇到错误是因为 get_event_loop creates the loop automatically only in the main thread. Create the loop manually with new_event_loop 像这样:

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