Python 在同一脚本中连接到同一API的2个连接。我需要两者都ping吗?
我正在连接一个允许订阅的API,因此每当Python 在同一脚本中连接到同一API的2个连接。我需要两者都ping吗?,python,websocket,Python,Websocket,我正在连接一个允许订阅的API,因此每当.recv()方法中出现新消息时,我都会读取它们,并将它们传递给主函数。如果我的程序空闲一段时间,这个API将自动断开任何连接。为了解决这个问题,他们每10秒ping一次我的程序(我可以调整),我需要响应他们发送一条test_消息,告诉服务器我没有空闲 我有一个脚本,格式如下: async def subscription_api(queue): #subscribe to various channels in the websocket and
.recv()
方法中出现新消息时,我都会读取它们,并将它们传递给主函数。如果我的程序空闲一段时间,这个API将自动断开任何连接。为了解决这个问题,他们每10秒ping一次我的程序(我可以调整),我需要响应他们发送一条test_消息,告诉服务器我没有空闲
我有一个脚本,格式如下:
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
这里我有两个问题:
async with websockets.connect(api)As ws:
)。这两个连接是否共享每个属性,或者它们是否算作到API的两个单独连接,因此我应该单独发送每个连接的测试消息,以便它们都“告诉”服务器它们不是空闲的?或者仅仅通过一个连接发送就足够了,因为它们共享相同的属性谢谢 2个连接就是2个连接你确定吗?因为每个连接都应该存在一个
connection.recv()
实例。但在我的例子中,我只有一个实例,在连接1中。因此,当我通过connection2发送消息时,服务器会给出一个答案,我可以通过connection1中的接收器获得答案。当我更仔细地阅读您的代码时,您有两个连接,但实际上只有一个连接在执行任何操作。您在subscription\u api
中连接了一个,在main
中连接了一个,您完全忽略了在main
中连接的一个。为什么?你是对的。我将代码分为两个连接,以使其更有条理。subscription\u api()
函数从服务器读取排队的消息,而main()
函数处理这些消息。它仍然需要一个连接,因为main()
向服务器发送一些请求,但来自它的所有响应都由subscription\u api()
管理,因此您有两个到服务器的连接。2个连接是2个连接。