Python Forum

Full Version: How to send a pong on websocket-client
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I have made a request to Binance websocket using the python websocket client, but the problem is that the websocket connection use to disconnect automatically.

When i check the documentation of the host they said i have to send a pong frame every time the server send a ping, and they said that the server use to send a ping every 3 mins.

Heres the section of the doc:
[attachment=1904]

Here's my try code:
all_market_tickers = '!ticker@arr'
url = f"wss://stream.binance.com:9443/ws"


subscribe = {
    "method": "SUBSCRIBE",
    "params":
        [
            all_market_tickers
        ],
    "id": 1
}


def on_message(ws, mesg):
  #do something with mesg received
  print(mesg) 




def on_open(ws):
    print("Opened connection")
    ws.send(json.dumps(subscribe))


def on_ping(ws, result):
    print('############# I HAVE BEEN PINGED') #I have not seen this line print before 
    print(result)
    ws.send(json.dumps(subscribe))


def on_pong(ws, pongista):
    ws.send(json.dumps(subscribe))


def on_close(ws):
    print("### closed ###")


def on_error(ws, error):
    print(error)
    print("They is err on_error")


def stream(url):
    websocket.enableTrace(True)
    ws = websocket.WebSocketApp(url,
                                on_open=on_open,
                                on_message=on_message,
                                on_error=on_error,
                                on_close=on_close,
                                on_ping=on_ping,
                                on_pong=on_pong)

    ws.run_forever(dispatcher=rel)  # Set dispatcher to automatic reconnection
    rel.signal(2, rel.abort)  # Keyboard Interrupt
    rel.dispatch()


if __name__ == "__main__":
    stream(url)
The connection works normally but it keeps disconnecting automatically.
I'm confident that I'm not doing the right thing here which is sending a pong when the server send a ping>
Please how can i send a pong?