首页 > 解决方案 > 2 个连接到同一脚本中的同一 API。我需要ping两个吗?

问题描述

我正在连接一个允许订阅的 API,所以每次方法中有新消息时我都会阅读它们,.recv()并将它们传递给主函数。如果我的程序空闲一段时间,此 API 将自动断开任何连接。为了解决这个问题,他们每 10 秒对我的程序执行一次 ping 操作(我可以对其进行调整),我需要响应他们发送一个 test_message 来告诉服务器我没有空闲。

我有一个表单的脚本:

async def subscription_api(queue):
    #subscribe to various channels in the websocket and pass the response to the main function
    async with websockets.connect(api) as ws:
        await ws.send(json.dumps(subscription_msg))
        response = json.loads(await ws.recv())
        await queue.put(response)


async def main():
    queue = asyncio.Queue()
    subscription = asyncio.create_task(subscription_api(queue))
    #I need this api connection to send messages to the server in this function
    async with websockets.connect(api) as ws:
        subscription = await queue.get()
        if subscription == 'ping':
            #if the message I receive from the server is a ping, send a test_message
        else:
            #do stuff

在这里我有两个问题:

  1. 即使我将这些 test_messages 发送回服务器,它仍然会不时断开连接(大约每 2-5 分钟一次),引发代码 1006 的异常(它没有指定原因)。知道为什么会这样,任何可能导致这种情况的常见错误吗?我一直在检查我的代码,但还没有找到原因。
  2. 如您所见,我的代码中有 2 个连接,每个函数都有一个连接 ( async with websockets.connect(api) as ws:)。这 2 个连接是否共享每个属性,或者它们是否算作 API 的 2 个单独连接,因此我应该为每个单独的连接发送测试消息,以便它们都“告诉”服务器它们没有空闲?或者仅仅在一个连接中发送它就足够了,因为它们再次共享相同的属性?

谢谢!

标签: pythonwebsocket

解决方案


推荐阅读