gpt4 book ai didi

python - 如何在 websockets 中使用多线程?

转载 作者:行者123 更新时间:2023-12-04 03:25:17 34 4
gpt4 key购买 nike

我正在尝试使用多线程的 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

最佳答案

看着websockets示例程序,你好像少了一条语句,loop.run_forever() ,这似乎有所作为(我还将 IP 地址更改为“localhost”以进行测试):


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

loop.run_until_complete(ws_server)
loop.run_forever() # this is missing
loop.close()
演示程序
注意更新的 hello避免 websockets.exceptions.ConnectionClosedOK: code = 1000 (OK), 在终止时没有理由异常的函数,我怀疑这是由于守护程序线程的终止而出现的。
import websockets
import threading
import asyncio

async def hello(websocket, path):
async for data in websocket:
print(f"Received: '{data}'")
await websocket.send(data)

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

loop.run_until_complete(ws_server)
loop.run_forever() # this is missing
loop.close()

async def send_receive_message(uri):
async with websockets.connect(uri) as websocket:
await websocket.send('This is some text.')
reply = await websocket.recv()
print(f"The reply is: '{reply}'")

def client():
loop = asyncio.new_event_loop()
asyncio.set_event_loop(loop)
loop.run_until_complete(send_receive_message('ws://localhost:8899'))
loop.close()

if __name__ == "__main__":
# daemon server thread:
server = threading.Thread(target=between_callback, daemon=True)
server.start()
client = threading.Thread(target=client)
client.start()
client.join()
打印:
Received: 'This is some text.'
The reply is: 'This is some text.'

关于python - 如何在 websockets 中使用多线程?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67734115/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com