Intermediate LevelNode JS
How do you configure socket.setKeepAlive() and socket.setTimeout() to detect dead TCP sockets?
❓ Interview Prompt: Call socket.setKeepAlive(true, 60000) to send TCP keep-alive probes. Call socket.setTimeout(30000) to catch idle sockets and close them cleanly on timeout.
Unmanaged TCP sockets can remain silently open indefinitely if network cables are unplugged without sending FIN packets:
•
'socket.setKeepAlive(true, 60000)': Sends periodic TCP keep-alive probe packets to detect dropped connections.
•
'socket.setTimeout(30000)': Triggers 'timeout' event if socket is idle for 30 seconds.
Code Implementation Example
javascript
import net from 'node:net';
const client = net.connect({ port: 9000 }, () => {
// Enable TCP keep-alive probes every 60 seconds
client.setKeepAlive(true, 60000);
// Destroy idle sockets after 30 seconds of inactivity
client.setTimeout(30000);
client.on('timeout', () => {
console.warn('Socket idle timeout! Destroying client socket...');
client.destroy();
});
});💡Configuring TCP keep-alive probes and socket idle timeouts.
🎯 Interview Key Takeaway
Configure socket.setKeepAlive and socket.setTimeout on long-lived TCP connections to detect silently dropped network sockets.
#socket#setKeepAlive#TCP#Timeout#Intermediate
Back to all Node JS Questions→