Python – How to send heartbeat using websocket-client?

Question:

The server requires the client to send a heartbeat every 30 seconds to keep the connection alive. How can I achieve this using python websocket-client library?

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(). How can I send messages ? Thank you

Asked By: musava_ribica

||

Answers:

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. If this is critical, I would use 14 seconds to make it more robust for network issues.

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()
Answered By: Chen A.

run_forever() method has ping_interval argument.
For example,

ws.run_forever(ping_interval=14)

can be used to automatically send “ping” command every specified period in seconds (here, it is 14 seconds).

You can also use ping_timeout which is a timeout (in seconds) if the pong message is not received.

More details are available in websocket docs: https://websocket-client.readthedocs.io/en/latest/app.html?highlight=run_forever#

Answered By: Tarak
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.