简体   繁体   English

Python - 如何使用 websocket-client 发送心跳?

[英]Python - How to send heartbeat using websocket-client?

The server requires the client to send a heartbeat every 30 seconds to keep the connection alive.服务器要求客户端每 30 秒发送一次心跳以保持连接处于活动状态。 How can I achieve this using python websocket-client library?如何使用 python websocket-client 库来实现这一点?

import websocket
def on_open(ws):
     pass
def on_close(ws):
     pass
def on_message(ws, message):
     pass

socket = "wss:// the rest of the url"
ws = websocket.WebSocketApp(socket, on_open=on_open,on_message=on_message)
ws.run_forever()

No code runs after ws.run_forever().在 ws.run_forever() 之后没有代码运行。 How can I send messages?如何发送消息? Thank you谢谢

In the library documentation there is a Long-lived connection example.在库文档中有一个长寿命连接示例。 Modifying it for your use case, it should look something like this.为您的用例修改它,它应该看起来像这样。 I used 28 seconds between heartbeats, since you said the 30 sec is the expected duration.我在两次心跳之间使用了 28 秒,因为您说 30 秒是预期的持续时间。 If this is critical, I would use 14 seconds to make it more robust for network issues.如果这很关键,我将使用 14 秒来使其对网络问题更加健壮。

import websocket
try:
    import thread
except ImportError:
    import _thread as thread
import time


.. code removed for brevity ..


def on_open(ws):
    def run(*args):
        while True:
            time.sleep(28)
            ws.send("Ping")

    thread.start_new_thread(run, ())


if __name__ == "__main__":
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp("ws://echo.websocket.org/",
                              on_message = on_message,
                              on_error = on_error,
                              on_close = on_close)
    ws.on_open = on_open
    ws.run_forever()

run_forever has ping_interval argument. run_forever 有 ping_interval 参数。 Eg.例如。 ws.run_forever( ping_interval=14) can be used for your purpose. ws.run_forever( ping_interval=14) 可用于您的目的。

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

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