title: node.js net.Socket socket.write() error handling
body: <p>I'd like to know if it's possible to detect if a server is offline when sending data using socket.write() on a net.Socket(). I would assume the error event or timeout event would be triggered after trying to write to a socket of a disconnected server but I cant get this to work. It just fires the socket.write and nothing happens. Here is some sample code.</p>
  
  <pre><code>try {
      socket = new net.Socket();
      socket.connect(data.port, data.address);
  } catch (error) {
      console.log(error);
  }
  
  socket.on('connect', function() {
      interval = setInterval(function() {
          socket.write('sending message');
      }, 1000);
  });
  
  socket.on('error', function(error) {
      clearInterval(interval);
      socket.destroy();
      socket.unref();
      console.log(error);
  });
  </code></pre>
  
  <p>[EDIT 1]</p>
  
  <p>A dirty solution would be the following code but this does not feel right. It sets a timer when writing to a socket. The timer is cancelled if data is received (which in my situation is the case after writing to the socket). If the timer is not cancelled the socket will be destroyed.</p>
  
  <pre><code>try {
      socket = new net.Socket();
      socket.connect(data.port, data.address);
  } catch (error) {
      console.log(error);
  }
  
  socket.on('connect', () =&gt; {
      interval = setInterval(function() {
          socket.write('sending message', () =&gt; {
              timeout = setTimeout(() =&gt; {
                  socket.destroy();
                  socket.unref();
              }, 4000);
          });
      }, 5000);
  });
  
  socket.on('error', (error) =&gt; {
      clearInterval(interval);
      socket.destroy();
      socket.unref();
      console.log(error);
  });
  
  socket.on('data', (message, address) =&gt; {
      clearTimeout(timeout);
  })
  </code></pre>