且构网

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

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

更新时间:2023-11-29 14:43:34

感谢Miroshko的 yojimbo87的回答,我能够捕获'close' ,但我不得不进行一些额外的调整。

0047
只是捕捉关闭事件的原因不是解决我的问题,是当客户端发送请求到node.js服务器,如果连接仍然打开,直到他发送回客户端(据我所知 - 这是因为HTTP协议),服务器本身无法获取信息。

因此,额外的调整是不时地写响应的响应。
$ $ $ $
另外一件事阻止这个工作,我有'Content-type'as'application / 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.