Heartbeat & reconnect
Send a ping every 30s to keep the connection alive. Auto-reconnect on close.
Code example
// client
setInterval(() => {
if (ws.readyState === WebSocket.OPEN)
ws.send(JSON.stringify({type: 'ping'}));
}, 30000);
ws.onclose = () => {
setTimeout(connect, 3000); // retry in 3s
};
How it works
WebSocket connections can be killed by idle timeouts (proxies often cut idle connections at 60s), network blips, or server restarts. Two defences: (1) heartbeat — send a ping every 30s to keep the connection 'active'; the server responds with pong. (2) auto-reconnect — on close, wait a few seconds and try again. The realtime.html page does both: every 30s it pings, and on close it retries in 3s. This makes the connection resilient to transient failures.
🔍 Where this is used in OpenBenchML
templates/realtime.html — ping every 30s + reconnect on close. templates/notebook.html — terminal heartbeat.