Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

closing a server after listening crashes with Not running exception

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!

Problem courtesy of: Asher Saban

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.

Solution courtesy of: Dr McKay

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

closing a server after listening crashes with Not running exception

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×