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?

ps-aux
  • 11,627
  • 25
  • 81
  • 128

3 Answers3

14

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

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();

Hussein Nasser
  • 402
  • 1
  • 6
  • 11