title: Node.js: client doesn't die when TCP connection closes
body: <p>I built a simple TCP server and a simple TCP client in Node.js</p>
  
  <p>Now, when the client sends "exit" to the server, the connection is successfully closed. The server deletes the socket from its sockets list and sends "Bye bye!" to the client.</p>
  
  <p>The connection on the client is closed as well but the app is still waiting for other inputs, so it doesn't die and I'm forced to type CTRL+C.</p>
  
  <p>I tried adding <code>process.exit()</code> after connection closes but it doesn't work:</p>
  
  <p><strong>CLIENT CODE:</strong></p>
  
  <pre><code>var net = require('net'),
      config = require(__dirname + '/config.json'),
      connection = net.createConnection(config.port, config.host);
  
  connection.setEncoding('utf8');
  
  connection.on('connect', function () {
      console.log('Connected');
  });
  
  connection.on('error', function (err) {
      console.error(err);
  });
  
  connection.on('data', function (data) {
      console.log('» ' + data);
  });
  
  connection.on('close', function() {
      console.log('Connection closed');
  });
  
  process.stdin.on('data', function (data) {
  
      if ((new String(data)).toLowerCase() === 'exit') {
          connection.end();
          process.exit();
      }
      else {
          connection.write(data);
      }
  
  });
  
  process.stdin.resume();
  </code></pre>
  
  <p><strong>SERVER CODE:</strong></p>
  
  <pre><code>var server = require('net').createServer(),
      config = require(__dirname + '/config.json'),
      sockets = [];
  
  server.on('connection', function (socket) {
      socket.setEncoding('UTF-8');
  
      socket.on('data', function (data) {
  
          console.log('Received data: ' + data);
  
          if (data.trim().toLowerCase() === 'exit') {
              socket.write("Bye bye!\n");
              socket.end();
          }
          else {
              sockets.forEach(function (client) {
                  if (client &amp;&amp; client != socket) {
                      client.write(data);
                  }
              });
          }
  
      });
  
      socket.on('close', function () {
          console.log('Connection closed');
          sockets.splice(sockets.indexOf(socket), 1);
  
          console.info('Sockets connected: ' + sockets.length);
      });
  
      sockets.push(socket);
  });
  
  server.on('listening', function () {
      console.log('Server listening');
  });
  
  server.on('close', function () {
      console.log('Server is now closed');
  });
  
  server.on('error', function (err) {
      console.log('error:', err);
  });
  
  server.listen(config.port);
  </code></pre>
  
  <p><strong>EDIT:</strong></p>
  
  <p>I added a client connection "on close" event handler. So, the string "Connection closed" is now printed by the server and by the client too.</p>