小编Kha*_*lil的帖子

如何通过 websocket 使用多线程?

我正在尝试使用多线程的 websocket ( https://websockets.readthedocs.io/en/stable/ )。我想要的是在程序继续运行时继续获取数据,但是,当我像下面的代码那样执行操作时,服务器没有收到来自客户端的任何连接。我之前在主线程上运行过它并且运行良好。

async def hello(websocket, path):
    while True:
        data = await websocket.recv()
        print(data)
        await websocket.send(data)


def between_callback():
    loop = asyncio.new_event_loop()
    asyncio.set_event_loop(loop)
    ws_server = websockets.serve(hello, '192.168.0.115', 8899)
    
    loop.run_until_complete(ws_server)
    loop.close()

if __name__ == "__main__":
    _thread = threading.Thread(target=between_callback)
    _thread.start()

  # Do something in main thread
Run Code Online (Sandbox Code Playgroud)

python multithreading websocket

4
推荐指数
1
解决办法
9964
查看次数

标签 统计

multithreading ×1

python ×1

websocket ×1