TJ66
January 10, 2023, 1:18pm
1
I’m connecting to a websocket (Spot) and receiving market data. I am not sending orders. Every 5 minutes I send a ping, to keep the connection alive.
Sometimes when I try to send a ping, the socket has been closed and I get a broken pipe error.
What reasons are there for Binance to close the connection?
dino
January 12, 2023, 12:13am
2
How long the connection got closed since it’s connected?
TS_ST
February 1, 2023, 11:23am
3
Websockets can be quite unstable depending on many aspects of your network, binance servers, and everything in between. It’s important to have logic monitoring your websocket health and handling it if the websocket seems to be dead. Here’s one approach to doing this in node.js:
The node.js connector (“binance” on npm, since there’s a few) handles this by sending ping frames as heartbeats every few seconds (ping interval):
This starts a race condition (pong timeout):
The healthy winner in this race is either a message OR a pong frame reply before the pong timeout:
If neither happens before the pong timer expires, the connection is assumed to be dead and killed/respawned to replace it with a fresh one:
This is the most resilient way I’ve seen to manage this regar…