【发布时间】:2021-05-31 12:13:34
【问题描述】:
我正在使用库websockets。
当尝试从多线程接收 websocket 的函数中接收数据时,出现错误。我无法克服它。我需要你的帮助!
我的代码:
async def receive_ws():
async with websockets.connect(uri, extra_headers=VALID_HEADERS) as websocket:
while True:
result = await websocket.recv()
print(result)
async def streams():
list_streams = []
for i in range(0, 100):
list_streams.append(str(i))
for j in list_streams:
await asyncio.to_thread(receive_ws)
asyncio.run(streams())
我的错误:
C:\Program Files\Python39\lib\asyncio\base_events.py:1891: RuntimeWarning: coroutine 'receive_ws' was never awaited
handle = None # Needed to break cycles when an exception occurs.
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
C:\Program Files\Python39\lib\concurrent\futures\thread.py:79: RuntimeWarning: coroutine 'receive_ws' was never awaited
del work_item
RuntimeWarning: Enable tracemalloc to get the object allocation traceback
【问题讨论】:
-
而不是
await asyncio.to_thread(receive_ws)你不能只做await receive_ws() -
我的目标 - 同时提供来自多个线程的 websockets
-
你真的需要多线程吗?
-
是的,我需要同时在多个线程中运行
-
那为什么要使用异步,通常你可以使用异步并避免使用线程,如果你只是从你的代码中看出来的网络绑定,那么你为什么需要线程?
标签: python-3.x websocket async-await