6

I use node.js (Express) with server-sent events. I would like to close the event stream by closing the sse HTTP connection. Given the folllwing function:

router.get('/sse', function (req, res) {

});

how can this be achieved?

1
  • this could be your solution as answered by @Mikael. Apr 19, 2016 at 4:32

3 Answers 3

15

How to hang up in ExpressJS

Ⅰ. End the response, keeping the socket connection alive.

response.end();

Ⅱ. “Could you please hang up first?”

Request the client to initiate the TCP socket connection termination sequence.

response.set("Connection", "close"); // Note: this is an HTTP header.

Ⅲ. Gently close the socket connection.

“Hey, I’ll be hanging up now, ’kay?”

TCP connection termination sequence

response.connection.end();

socket.end([data[, encoding]][, callback])

Half-closes the socket. i.e., it sends a FIN packet. It is possible the server will still send some data.

See writable.end() for further details.

Ⅳ. Just hang up on the client aggressively. No FIN packet, even.

response.connection.destroy();

socket.destroy([error])

Ensures that no more I/O activity happens on this socket. Destroys the stream and closes the connection.

See writable.destroy() for further details.

12

use this

res.end();

and it will work to close connection

1
  • 8
    this ends response, but doesn't close TCP connection.
    – Pavel P
    Nov 24, 2018 at 5:44
4

Selected answer is incorrect, res.end() ends the response and writes to the socket. But it doesn't close the TCP connection.

You need to get the underlying connection from the res object and call end on it to close it.

res.connection.end();

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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