How to close a “Server-Sent Events”-connection on the server?

北慕城南 提交于 2019-12-24 17:07:02

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!