I’m using websocket market streams in a node js application with ws library 1. It receives data all right but connection gets closed every 10 minutes. I’ve tried listening to ping events with ws.onping but it never gets triggered which makes me thing that the server never sends the ping frame. How can I send a ping message to the server? I’ve tried ws.send(‘ping’) but the server responses with { error: { code: 3, msg: ‘Invalid JSON: expected value at line 1 column 1’ } }. What is the correct format for the ping message?
Alright so the code I provided you with is for a node js application as well and it works since I’m using this exact code. It specifies directly to listen to the ping event instead of calling the wrapper, but it’s essentially doing the same, only the syntax for its usage differs. My guess would be that you’re using the wrong syntax for your callback upon receival of the ping request which then leads you to think you’re not receiving a ping from the server.
So now for completeness, here are the two syntaxes.
Specifying the event to listen to:
ws.on('ping', (e) => { //Defines callback for ping event
ws.pong(); //send pong frame
});
Using the wrapper like you:
ws.onping = () => { //Defines event handler for ping event
ws.pong(); //send pong frame
};
Now that it’s out of the way, once again, you DO NOT need to send a ping
, BUT a pong
request instead to the server. (Server sends ping
, you answer pong
… Like ping-pong 2, you know…).
Finally, to send that pong
request, as stated in my previous response, you simply need to call ws.pong()