title: Wait/reconnect until TCP client connection can be established?
body: <p>Here is an example of how to create a TCP client connection from the node net docs (<a href="https://nodejs.org/api/net.html#net_net_connect_options_connectlistener" rel="nofollow noreferrer">https://nodejs.org/api/net.html#net_net_connect_options_connectlistener</a>)</p>
  
  <pre><code>const client = net.createConnection({ port: 1905 }, () =&gt; {
      // 'connect' listener
      console.log('connected to server!');
      client.write('world!\r\n');
  });
  client.on('data', (data) =&gt; {
      console.log(data.toString());
      client.end();
  });
  client.on('end', () =&gt; {
      console.log('disconnected from server');
  });
  </code></pre>
  
  <p>If the server is not available I get <code>Error: connect ECONNREFUSED 127.0.0.1:1905</code>.</p>
  
  <p>What would be a good way to wait/reconnect until the server is available and connect when it is, instead of throwing an error?</p>
  
  <p>EDIT: Here is an alternative approach I have tried, but here I get the problem</p>
  
  <blockquote>
    <p>MaxListenersExceededWarning: Possible EventEmitter memory leak
    detected. 11 connect listeners added. Use emitter.setMaxListeners() to
    increase limit</p>
  </blockquote>
  
  <p>I would like the latest listener to replace earlier listeners. They all listen for the same thing. I just want to retry.</p>
  
  <pre><code>function initTcpClient() {
      console.log("Initiating TCP client...")
      var tcpSocket = new net.Socket();
      const client = net.createConnection({ port: 1905 }, () =&gt; {
  
      tcpSocket.on('error', function onError(err) {
          setTimeout(connect, 1000);
      });
  
      connect();
  
      function connect() {
          console.log("Looking for TCP server...");
          tcpSocket.connect(argv.tcpport, argv.tcphost, function onConnected() {
              console.log("Connecting to TCP server...");
              tcpSocket.on('data', function onIncoming(data) {
                  if (connectedWebsocketClient) {
                      console.log('Forwarding to WebSocket: %s', data);
                      webSocketClient.send(data.toString());
                  } else {
                      console.log('Not connected to websocket client. Dropping incoming TCP message: %s', data);
                  }
              });
              tcpSocket.on('close', function onClose(hadError) {
                  console.log("Connection to TCP server was closed.");
                  connectedToTcpServer = false;
                  setTimeout(connect, 1000);
              });
              console.log("Connected to TCP server.");
              connectedToTcpServer = true;
          });
  
      }
  
  }
  </code></pre>