24

Is there a way to close a response? I can use res.end() but it doesn't actually close the socket.

What I want to achieve: I am writing a Java program which interfaces with the network, and I am writing a NodeJS server for this. Java code:

String line;
while((line = in.readLine()) != null) {
    System.out.println("RES: "+line);
}

But this just keeps hanging. No end connection, still waiting for input from the socket.

Node:

exports.getAll = function (req, res) {
    res.set("Content-Type", "text/plain");
    res.set(200);
    res.send(..data..);
    res.end();
}

however res.end() does not close the connection. As said before, Java keeps thinking there will be something next so it is stuck in the while loop.

Rafael Tavares
  • 5,678
  • 4
  • 32
  • 48
Matej
  • 9,548
  • 8
  • 49
  • 66

2 Answers2

38

Solved by setting a HTTP header to close the connection instead of default keep-alive strategy.

res.set("Connection", "close");
Matej
  • 9,548
  • 8
  • 49
  • 66
  • 1
    is there any way I can hook it as default to all responses? – Abhishek Deb Nov 19 '14 at 10:34
  • 4
    @AbhishekDeb if you create a middleware that sets the above header then it will work for all requests – Matej Nov 19 '14 at 11:12
  • 4
    Surely this just tells the remote side to close the connection. You are not closing the connection if you are sending headers back in the response. – Phil Sep 04 '17 at 08:10
  • 2
    node might be (by default) keeping the connection open (keep-alive) strategy – Matej Sep 04 '17 at 14:34
16

In case someone who really wants just to close the connection finds this, you can use res.socket or res.connection to get the net.Socket object which comes with a destroy method:

res.connection.destroy();
Spect
  • 161
  • 1
  • 4
  • 1
    This is exactly what I needed to simulate a drop in network availability for automated tests without actually disabling the internet connection manually. – zivc Aug 27 '19 at 10:53