且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何检查 node.js 服务器中的连接是否中止

更新时间:2023-11-29 14:47:28

感谢 Miroshkoyojimbo87 的回答,我能够赶上 'close' 事件,但我不得不做一些额外的调整.

仅仅捕获关闭"事件并没有解决我的问题的原因是,当客户端将请求发送到 node.js 服务器时,如果连接仍然打开,服务器本身无法获取信息,直到他将某些内容发送回客户端(据我所知 - 这是因为 HTTP 协议).
因此,额外的调整是不时为响应写入一些内容.
阻止此工作的另一件事是我将内容类型"设为应用程序/json".将其更改为text/javascript"有助于在不关闭连接的情况下不时流式传输空白".
最后,我得到了这样的东西:

Thanks to Miroshko's and yojimbo87's answers I was able to catch the 'close' event, but I had to make some additional tweaks.

The reason why just catching 'close' event wasn't fixing my problem, is that when client sends the request to the node.js server, the server itself can't get information if the connection is still open until he sends something back to the client (as far as I understood - this is because of the HTTP protocol).
So, the additional tweak was to write something to the response from time to time.
One more thing that was preventing this to work, is that I had 'Content-type' as 'application/json'. Changing it to 'text/javascript' helped to stream 'white spaces' from time to time without closing the connection.
In the end, I had something like this:

var server = http.createServer(function(req,res){    
    res.writeHead(200, {'Content-type': 'text/javascript'});

    req.connection.on('close',function(){    
       // code to handle connection abort
    });

    /**
     * Here goes some long polling handler
     * that performs res.write(' '); from time to time
     */

    // some another code...
});
server.listen(NODE_PORT, NODE_LISTEN_HOST);

我的原始代码要大得多,所以为了显示敏感部分,我不得不把它剪掉很多.

My original code is much bigger, so I had to cut it a lot just to show the sensitive parts.

我想知道是否有更好的解决方案,但目前这对我有用.

I'd like to know if there are better solutions, but this is working for me at the moment.