python - 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
在这里我有两个问题:
- 即使我将这些 test_messages 发送回服务器,它仍然会不时断开连接(大约每 2-5 分钟一次),引发代码 1006 的异常(它没有指定原因)。知道为什么会这样,任何可能导致这种情况的常见错误吗?我一直在检查我的代码,但还没有找到原因。
- 如您所见,我的代码中有 2 个连接,每个函数都有一个连接 (
async with websockets.connect(api) as ws:
)。这 2 个连接是否共享每个属性,或者它们是否算作 API 的 2 个单独连接,因此我应该为每个单独的连接发送测试消息,以便它们都“告诉”服务器它们没有空闲?或者仅仅在一个连接中发送它就足够了,因为它们再次共享相同的属性?
谢谢!
解决方案
推荐阅读
- php - Liip - 仅在大于预期时调整图像大小
- jenkins - 有什么方法可以一次性更新所有 Jenkins 作业的配置(描述)而无需手动操作?
- java - 无法从 Java 在 iOS(Swift)中解密(AES)
- docker - 无法创建没有匹配网关的 Docker 网络
- javascript - useEffect 中的一个简单事件侦听器导致多个警告
- python - 从终端运行时没有在 Python 中创建换行符的打印问题
- google-cloud-platform - GCP 中的错误:无法更改实例组的实例模板
- typescript - 我使用了 node.js 的内置函数。如何修复“TypeError:__WEBPACK_IMPORTED_MODULE_3_fs__.writeFile 不是函数”
- java - 使用 Primeface DefaultStreamedContent 查看中文内容 PDF 时出现 InvalidPDFException
- python - 如何从查询集中选择数据并按特定日期的计数分组