title: How to properly destroy a socket so that it is ready to be called again after program exits? (Node.js)
body: <p>He is a bit of code where a server is created to listen on port 2222:</p>
  <pre class="lang-js prettyprint-override"><code>import { createServer } from 'net';
  
  const server = createServer((c) =&gt; {
    c.setEncoding('utf8');
    c.on('data', (data) =&gt; {
      console.log('server', data);
      c.write(data);
    });
    c.on('error', (e) =&gt; { throw e; });
  });
  server.listen(2222);
  </code></pre>
  <p>and the code to create a connection to the server to send a simple 'hello' that the server will respond back to. After 2 seconds, the socket gets destroyed.</p>
  <pre class="lang-js prettyprint-override"><code>import { createConnection } from 'net';
  
  const socket = createConnection({ localPort: 9999, port: 2222, host: 'localhost' });
  socket.setEncoding('utf8');
  socket.on('data', (data) =&gt; {
    console.log('socket data', data);
  });
  socket.on('connect', () =&gt; {
    socket.write('hello');
  });
  socket.setTimeout(2000);
  socket.on('timeout', () =&gt; { socket.destroy(); console.log('destroyed'); });
  socket.on('error', (e) =&gt; { throw e; });
  </code></pre>
  <p>This code works well the first time it is called.</p>
  <p>It will fail on subsequent calls with:</p>
  <pre><code>Error: connect EADDRINUSE 127.0.0.1:2222 - Local (0.0.0.0:9999)
    errno: -48,
    code: 'EADDRINUSE',
    syscall: 'connect',
    address: '127.0.0.1',
    port: 2222
  </code></pre>
  <p>It took me a while to figure it out, but the problem comes from trying to bind the socket on an outbound port: <code>localPort: 9999</code>. Without specifying this parameter, the OS will select a free port, and the program won't crash.</p>
  <p>When specifying it, a cooldown of ~15s is required before the socket being re-usable again.</p>
  <ul>
  <li>Is there a way to properly destroy the socket so that it becomes immediately available again?</li>
  <li>If not, is there a way to verify that the socket is &quot;cooling down&quot;, but will eventually be available again? I'd like to distinguish the case where I just have to wait from the one where the socket has been actively taken by another process, and won't be released to the pool of free sockets.</li>
  </ul>
  <p>Any theory on why the socket is not available after the program exists is welcome!</p>