-1

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.

Community
  • 1
  • 1
Giang Pham
  • 41
  • 5

1 Answers1

0

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.

user207421
  • 305,947
  • 44
  • 307
  • 483
  • 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 https://docs.oracle.com/javase/7/docs/api/java/net/ConnectException.html and here https://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 Oct 05 '16 at 00:32