Course contentsShow
← Node.js
Lesson 517 of 1,9806. Networking and HTTP FundamentalsFree lesson

Detecting Socket Hang-ups

Implement event listeners to gracefully handle unexpected client disconnections during data streaming.

In this lesson, you will learn how to gracefully detect and respond to unexpected client disconnections when streaming data over a network socket.

The Reality of Network Instability

When you stream data to a client, you might assume the connection will remain open until your server decides to finish the transmission. However, in the real world, connections are fragile. A client might lose Wi-Fi, force-close their application, or experience a network timeout. When this happens, the socket "hangs up," but your server might still be busy processing or streaming data into a void.

Detecting the Hang-up

In Node.js, a socket is essentially a stream.Duplex object. To prevent wasting memory or CPU cycles on a "ghost" connection, you must listen for the 'close' or 'error' events. If a client disconnects unexpectedly, the underlying TCP connection emits a signal that tells your program the party on the other end is gone.

Here is how you handle this pattern:

const net = require('net');

const server = net.createServer((socket) => {
  console.log('Client connected');

  // Handle the unexpected hang-up
  socket.on('close', (hadError) => {
    if (hadError) {
      console.log('Socket closed due to a transmission error');
    } else {
      console.log('Client disconnected gracefully');
    }
    // Logic to clean up resources, like stopping an active data feed
  });

  // Example: Streaming data to the socket
  socket.write('Sending critical stream data...');
});

Why This Matters

If you don't listen for these events, your server may continue to push data into a buffer that has nowhere to go. This leads to memory bloat—where your server holds onto data buffers intended for a client that no longer exists. By implementing these listeners, you ensure that as soon as the connection state shifts, your application can stop the stream, clean up associated resources (like file handles or database queries), and free up memory for other active users.

Key Takeaway: Always attach 'close' and 'error' listeners to your sockets to detect unexpected disconnections, allowing you to stop data transmission and reclaim resources immediately.