问题
Regarding this specification: http://www.w3.org/TR/eventsource/
How does one close the opened connection on the server? Client-side wise it is easy, just call close()
, but what should I do on the server? Just kill it?
回答1:
node.js:
http.createServer(function (req, res) {
//...
// client closes connection
res.socket.on('close', function () {
res.end();
//...
});
});
see example for implementation of SSE server in node.js:
https://github.com/Yaffle/EventSource/blob/master/nodechat/server.js
回答2:
you can change the content-type the server sents other than "text/event-stream". This will close the clients eventsource.
回答3:
I guess you just close the connection (kill it). I have not seen any talk about graceful disconnect.
回答4:
Caution: If you use a package to manage server-sent events in node.js, making a direct call to response.end()
may cause the package to send additional data after response.end()
, and this will crash the server with a "WRITE after close" error.
Instead of directly calling response.end()
, my workaround was to call response.emit('close')
, which allowed the package to handle the close.
Node.js documentation on http.ServerResponse > Event.close:
https://nodejs.org/api/http.html#http_event_close_1
来源:https://stackoverflow.com/questions/6534572/how-to-close-a-server-sent-events-connection-on-the-server