python - 使用 websocket.send(msg) 一段时间后出现 "got Future <Future pending> attached to a different loop"错误

标签 python websocket async-await runtime-error python-asyncio

我正在使用 websocket 在 python 中发送和接收消息。我使用“websocket.send(msg)”以这些形式发送消息:

await ws.send(message)

asyncio.run(ws.send(message))

在 while 循环中,我首先检查连接是否处于事件状态,然后使用这些命令发送消息。在所有这些中,如果发送次数较少,没有问题,但是当发送次数增加时,我会收到发送消息的异常

Task <Task pending coro=<RunSocket() running at <ipython-input-1-b17eaf75a3de>:182> cb=[_run_until_complete_cb() at D:\Anaconda\InstallationFolder\lib\asyncio\base_events.py:158]> got Future <Future pending> attached to a different loop

“请注意,RunSocket 是我的函数名称之一”

然后我收到此错误:

got Future <Future pending> attached to a different loop

我也尝试了这段代码:

asyncio.ensure_future(await ws.send(message))

但它没有发送任何消息。谁能帮我解决这个错误? 任何帮助将不胜感激。

最佳答案

got Future attached to a different loop

当您创建一些异步对象时,它会附加到 current事件循环(主线程默认有一个)。 当相同的事件循环处于当前状态时,预计将使用异步对象。 asyncio.run 创建新的事件循环并将其设置为当前事件循环。 结果是 - 您已将异步对象附加到一个事件循环,但尝试将其与另一个事件循环一起使用。这就是错误的来源。

为了避免这种情况,您应该在 asyncio.run 创建新事件循环后创建异步对象:

async def main():
    ws = ...  # create object after asyncio.run is started
    res = ws.send(message)
    return res

asyncio.run(main())

关于python - 使用 websocket.send(msg) 一段时间后出现 "got Future <Future pending> attached to a different loop"错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60066383/

相关文章:

iis - IIS 上托管的 ASP.NET 5 (DNX) 中的 WebSocket 无法正常工作

Angular:Async Await- promise 中的 EventListener

python - 使用 Django 表单编辑图像字段

python - Django 1.6 Block Trans 无法使用变量

javascript - openshift/nodeJS 中的 Websocket 失败

c# - Task.Delay 中委托(delegate)未执行后的代码

c# - Y型任务执行

python - 从单个 python 脚本或 GUI 按钮运行服务器和客户端 python 脚本

python - 使用正则表达式反向搜索

javascript - 无法连接到本地 Node.js 安全 WebSocketServer