title: Nodejs - getting client socket to try again after 5 sec time out
body: <p>Just starting out in node.js programming and writing a tcp socket client.</p>
  
  <p>I want the client to connect to a server. If the server is not available (i.e. server does not exist at a agreed port), i want the client to timeout and reconnect after the timeout.</p>
  
  <p>I have this code but it hangs at the second client.connect. What's wrong?</p>
  
  <pre><code>var net = require('net');
  var HOST = '127.0.0.1';
  var PORT = 9000;
  var client = new net.Socket();
  
  client.connect(PORT, HOST, function(){
      console.log('CONNECTED TO: ' + HOST + ':' + PORT);
      client.write('I am Superman!');
  });
  
  client.on('error', function(e) {
      while (e.code == 'ECONNREFUSED') {
          console.log('Is the server running at ' + PORT + '?');`
  
          socket.setTimeout(1000, function() {
              console.log('Timeout for 5 seconds before trying port:' + PORT + ' again');
          }
  
          client.connect(PORT, HOST, function(){
              console.log('CONNECTED TO: ' + HOST + ':' + PORT);
              client.write('I am the inner superman');
          });
      }); 
  });
  </code></pre>
  
  <p>Updated code:</p>
  
  <pre><code>var net = require('net');
  var HOST = '127.0.0.1';
  var PORT = 9000;
  var client = new net.Socket();
  
  client.connect(PORT, HOST, function(){
      console.log('CONNECTED TO: ' + HOST + ':' + PORT);
      client.write('I am Superman');
  });
  
  client.on('error', function(e) {
  
      while (e.code == 'ECONNREFUSED') {
          console.log('Is the server running at ' + PORT + '?');
  
          client.setTimeout(4000, function() {
  
              client.connect(PORT, HOST, function() {
                  console.log('CONNECTED TO: ' + HOST + ':' + PORT);
                  client.write('I am inner Superman');
              });         
  
              console.log('Timeout for 5 seconds before trying port:' + PORT + ' again');
          });
      }
  });
  
  client.on('data', function(data) {
      console.log('DATA: ' + data);
      client.destroy();
  });
  
  client.on('close', function() {
      console.log('Connection closed');
  });
  </code></pre>
  
  <p>With the updated code, the timeout does not appear to take effect. When i start this client with no corresponding server, the result shows below with no 4 second wait.</p>
  
  <pre><code>Is the server running at 9000?
  Is the server running at 9000?
  Is the server running at 9000?
  Is the server running at 9000?
  …
  </code></pre>
  
  <p>Update (Barking up the wrong tree?)</p>
  
  <p>I went back to look at the socket.on('error') event and saw that the close event is called immediately after the error. So the code will close out the tcpclient without waiting for 4 seconds. Any better ideas?</p>