closing a server after listening crashes with Not running exception
Problem
i have the following code:
var net = require('net');
var server = net.createServer(function (stream) {
console.log("request");
});
console.log("== 1");
server.listen(8124, 'localhost',function(){console.log("listening");});
console.log("== 2");
server.close();
the output is:== 1
== 2
and then the net module throws the exception of Not running
.
in the node.js docs it's written that:
Stops the server from accepting new connections. This function is asynchronous, the server is finally closed when the server emits a 'close' event.
if it's asynchronous then why do i get that output? it should listen first and then close it.
thanks!
Solution
There's no guarantee that Server will start listening before you close it (because listening is asynchronous).
Closing the server like:
server.listen(8124, 'localhost', function () {
console.log("listening");
server.close();
});
should work.
Discussion
View additional discussion.