title: Reconnect net.socket nodejs
body: <p>I am new to node.js and would like to connect to a TCP socket. For this I am using the net module.</p>
  
  <p>My idea was to wrap the connect sequence into a function then on the 'close' event, attempt a reconnection. Not that easy apparently.</p>
  
  <pre><code>function conn() {
  
      client.connect(HOST_PORT, HOST_IP, function() {
          startSequence();
      })
  }
  
  client.on('close', function(e) {
      log('info','Connection closed! -&gt; ' + e)
      client.destroy();
      setTimeout(conn(),1000);
  });
  </code></pre>
  
  <p>So when the remote host is closed, I see my logs comming through, howere what seems to be happening is that as soons as the remote host comes online ALL the previous attempts start to get processed - if that makes sense. If you look at client.connect, there is a function called startSequence that sends some data that "iniates" the connection from the remote server side. When the server goes offline and I start reconnecting all the failed attempts from before seem to have been buffered and are all sent together when the server goes online.</p>
  
  <p>I have tried the code from this Stackoverflow link as well to no avail (<a href="https://stackoverflow.com/questions/19981040/nodejs-getting-client-socket-to-try-again-after-5-sec-time-out">Nodejs - getting client socket to try again after 5 sec time out</a>)</p>
  
  <pre><code>client.connect(HOST_PORT, HOST_IP, function() {
      pmsStartSequence();
  })
  
  
  // Add a 'close' event handler for the client socket
  client.on('close', function(e) {
      log('debug','connection  closed -&gt; ' + e)
      client.setTimeout(10000, function() {
          log('debug', 'trying to reconnect')
          client.connect(HOST_PORT, HOST_IP, function() {
              pmsStartSequence();
          })
      })
  });
  </code></pre>
  
  <p>Is there any advice on how I can reconnect a socket after failure?</p>