首页 > 解决方案 > Python - 如何使用 websocket-client 发送心跳?

问题描述

服务器要求客户端每 30 秒发送一次心跳以保持连接处于活动状态。如何使用 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()

在 ws.run_forever() 之后没有代码运行。如何发送消息?谢谢

标签: pythonwebsocket

解决方案


在库文档中有一个长寿命连接示例。为您的用例修改它,它应该看起来像这样。我在两次心跳之间使用了 28 秒,因为您说 30 秒是预期的持续时间。如果这很关键,我会使用 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()

推荐阅读