title: Nodejs: This socket is closed
body: <p>I am using tcp sockets in Node.js to communicate with a Java client.</p>
  
  <p>See my very basic server implementation below:</p>
  
  <pre><code>var server = my_http.createServer();
  echo.installHandlers(server, {
      prefix: '/echo'
  });
  server.listen(8000, '0.0.0.0');
  
  var socketServer = net.createServer(function (socket) {
  
      // Identify this client
      socket.name = socket.remoteAddress + ":" + socket.remotePort
  
      // Put this new client in the list
      clients.push(socket);
  
      sockets[socket.name] = socket;
  
      // Handle incoming messages from clients.
      socket.on('data', function (data) {
  
          try {
              var obj = JSON.parse(data);
  
              if (obj.type == "sendMessage") {
                  broadcast("{\"id\":\"1\", \"msg\": \"" + obj.msg + "\", \"name\": \"" + obj.name + "\", \"time\": \"" + getDateTime() + "\"}\n", socket);
  
              }
          } catch (er) {
  
          }
      });
  
      // Remove the client from the list when it leaves
      socket.on('end', function () {
          try {
              clients.splice(clients.indexOf(socket), 1);
          } catch (err) {
  
          }
      });
  
      // Send a message 
  
      function broadcast(message, sender) {
          try {
              clients.forEach(function (client) {
                  client.write(message); // ERROR IS HERE
              });
          } catch (ee) {
  
          }
      }
  
      return socket;
  }).listen(8080);
  </code></pre>
  
  <p>For some reason sometimes i get this error: </p>
  
  <p><code>events.js:71
          throw arguments[1]; // Unhandled 'error' event
                         ^
  Error: This socket is closed.</code></p>
  
  <p>Its happening on this line:</p>
  
  <p><code>client.write(message); // ERROR IS HERE</code></p>
  
  <p>Any ideas how to prevent this from happening? </p>