简体   繁体   English

如何使用 Python websockets 库在“ping”调用中获得“pong”响应?

[英]How to get the "pong" response on "ping" call using Python websockets library?

I have an application that subscribes to a web-socket and, from time to time, receives from it some information.我有一个订阅网络套接字的应用程序,并且不时从中接收一些信息。 In some cases it might happen that my application does not receive anything for a relatively long time.在某些情况下,我的应用程序可能会在相对较长的时间内没有收到任何内容。 In that case I might suspect that web-socket have "died".在那种情况下,我可能会怀疑 web-socket 已经“死了”。 However, it might also be the case that web-socket just does not have anything to send and I just need to wait longer.但是,也可能是 web-socket 没有任何东西要发送,我只需要等待更长时间。

So, in such situations I do not want to guess what was the reason for the delay.所以,在这种情况下,我不想猜测延迟的原因是什么。 I just want "actively" ask the web-socket if it is still alive.我只想“主动”询问网络套接字是否还活着。 I have learned that one can do it with "ping" but I am not sure how exactly it works.我了解到可以用“ping”来做到这一点,但我不确定它究竟是如何工作的。

For example I can do the follwing:例如,我可以执行以下操作:

pong_waiter = await ws.ping()

But what I should do with this object?但是我应该用这个对象做什么? I guess I need to see a "pong" string when the web-socket is alive, but where can I see it?我想当网络套接字处于活动状态时我需要看到一个“pong”字符串,但是我在哪里可以看到它? What does return this string?返回这个字符串是什么?

ADDED添加

If I execute:如果我执行:

pong_waiter = await ws.ping()
await pong_waiter

I did not get anything.我什么也没得到。 After that I also execute:之后我也执行:

pong_waiter.result()

It also returns nothing.它也不返回任何内容。 But I know what web-socket is alive (I am still getting information from it).但我知道什么是网络套接字(我仍在从中获取信息)。

ADDED 2添加 2

If I execute:如果我执行:

pong_waiter

I get:我得到:

<Future finished result=None>

So, where is "pong"?那么,“乒乓”在哪里?

You should await it if you want to wait for the pong :如果你想等待pong你应该await它:

pong_waiter = await ws.ping()
await pong_waiter

If you expect the pong to contain a custom payload, you can most likely get it from the pong_waiter Future by calling result() after it completes.如果您希望pong包含自定义负载,您很可能可以通过在pong_waiter Future完成后调用result()它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM