Binance websocket ping/pong frame

I’m working with Binance API, specifically with websocket endpoint, to receive updats to the best bid or ask’s price or quantity in real-time for a specified symbol using Python and websocket-client library. Everything works just fine, until a ping frame is received from the Binance, it fails with code 1008 and then connections is closed. Here is my code:

ws = websocket.WebSocketApp(
        self.SOCKET_URL,
        on_message=_on_message,
        on_open=_on_open,
        on_error=_on_error,
        on_close=_on_close,
        on_ping=_on_ping,
)
def _reconnect(self, ws: websocket.WebSocketApp):
    if ws.sock is not None:
        if ws.sock.connected:
            return
        else:
            ws.close()

    self.clear_database()

    ws.run_forever(http_proxy_port=8080, ping_interval=60)
    if ws.sock is not None and ws.sock.connected:
        return

    logger.info("[SOCKET Close] %s provider. Unable to reconnect, need to do it manually",
                self.provider.name)
    ws.close()

def _on_error(self, ws, error):
    self._reconnect(ws)

    logger.info('[SOCKET Err] %s provider: %s', self.provider.name, error)

def _on_close(self, ws, _, close_msg):
    logger.info("[SOCKET Close] %s provider: %s. Code %s", self.provider.name, close_msg, _)

    self._reconnect(ws)

def _on_ping(self, ws, *_):
    ws.send(websocket.ABNF.OPCODE_PING)

In on_ping i send websocket.ABNF.OPCODE_PING because I saw it in the websocket-client library source code.

I tried to remove on_ping handler from WebsocketApp initialization, hoping that library takes care of the incoming ping messages itself - no luck. Also setting ping_interval didn’t help. I also tried to send different data inside on_ping handler, such as:

ws.send('PING')

or just reflect incoming message like this

def _on_ping(self, ws, *_):
    ws.send(*_)

If you see the code of this library, it automatically respond PONG message to client when a PING message is received. So you dont need to do it manually.

ws.send('PING')

is trying to sending “PING” string as data frame, that’s not valid message that server can accept. That’s why server reject and disconnect the connection.

@dino thanks for the reply.

But I also tried reflect the incoming message or send ping opcode, as well as don’t send anything as i saw in the library docs that it takes care of ping/pong frame itself. Am i missing something?

there is one way you can test out if setup a local websocket server, and ping your client and see if pong message can be received.