0

I'm having a tough time writing a test for a feature intended to be in a live reload developer environment. Basically I'd like to

  • Start a dumb server on localhost:9876
  • Close it
  • Start it again on the same host and port
  • Close it again

But upon starting it again I get a EADDRINUSE error, despite closing the server and dereferencing it.

Here's my code so far:

const net = require('net');
const server = net.createServer();
server.listen(9876, 'localhost');
server.close(() => {
    server.unref();
    const anotherServer = net.createServer();
    anotherServer.listen(9876, 'localhost');
});

I'm guessing that it has something to do with me not sure of the inner workings of the node TCP Server...

navelencia
  • 111
  • 1
  • 4
  • 1
    Does this answer your question? [How to properly \`close\` a node.js server?](https://stackoverflow.com/questions/26740988/how-to-properly-close-a-node-js-server) – Entity Black Jun 29 '21 at 15:45
  • 2
    From what I know, closing server will not accept new connections, but keeps existing connections. You also need to kill those to free the port I belive. – Entity Black Jun 29 '21 at 15:46
  • Well in this specific use case there aren't any connections made, so nothing to keep alive. It's just a start/stop/start of the server. Still, maybe there's a connection happening behind my back that I don't know, i'll give it a look – navelencia Jun 29 '21 at 20:07

1 Answers1

0

Well I think I found the culprit. It seems that specifying the hostname is what causes this error in that case. If you just delete the hostname and make the code look like this it works just fine.

const net = require('net');
const server = net.createServer();
server.listen(9876);
server.close(() => {
    server.unref();
    const anotherServer = net.createServer();
    anotherServer.listen(9876);
});

It's not an ideal answer because I don't understand the root of the issue here, but this "trick" seems to fix it.

navelencia
  • 111
  • 1
  • 4