Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

So I modified the accepted answer in this thread How do I shutdown a Node.js http(s) server immediately? and was able to close down my nodejs server.

// Create a new server on port 4000
var http = require('http');
var server = http.createServer(function (req, res) { res.end('Hello world!'); }).listen(4000);

// Maintain a hash of all connected sockets
var sockets = {}, nextSocketId = 0;
server.on('connection', function (socket) {
  // Add a newly connected socket
  var socketId = nextSocketId++;
  sockets[socketId] = socket;
  console.log('socket', socketId, 'opened');

  // Remove the socket when it closes
  socket.on('close', function () {
    console.log('socket', socketId, 'closed');
    delete sockets[socketId];
  });

});


...
when (bw == 0) /*condition to trigger closing the server*/{
  // Close the server
  server.close(function () { console.log('Server closed!'); });
  // Destroy all open sockets
  for (var socketId in sockets) {
    console.log('socket', socketId, 'destroyed');
    sockets[socketId].destroy();
  }
}

However, on the client side, the client throws a ConnectionException because of the server.close() statement. I want the client to throw a SocketTimeoutException, which means the server is active, but the socket just hangs. Someone else was able to do this with a jetty server from Java

Server jettyServer = new Server(4000);
...
when (bw == 0) {
  server.getConnectors()[0].stop();
}

Is it possible to achieve something like that? I've been stuck on this for a while, any help is extremely appreciated. Thanks.

share|improve this question

What you ask is impossible. A SocketTimeoutException is thrown when reading from a connection that hasn't terminated but hasn't delivered any data during the timeout period.

A connection closure does not cause it. It doesn't cause a ConnectionException either, as there is no such thing. It causes either an EOFException, a null return from readLine(), a -1 return from read(), or an IOException: connection reset if the close was abortive.

Your question doesn't make sense.

share|improve this answer
    
Maybe I wasn't clear enough. A connection closure does cause ConnectException when a client attempts to connect after the closure happened, because the server stops accepting new connection. You can read about this here docs.oracle.com/javase/7/docs/api/java/net/… and here nodejs.org/api/net.html#net_server_close_callback. That part worked for me as expected. Anyway, I figured out how to create the SocketTimeoutException also. So thanks. – Giang Pham 50 mins ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.