如何检查在node.js服务器中是否中止连接 [英] How to check if connection was aborted in node.js server

查看:172
本文介绍了如何检查在node.js服务器中是否中止连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用node.js进行一些长时间轮询。

基本上,node.js服务器接受来自用户的请求,然后检查一些更新。如果没有更新,它会在超时后检查它们。

但是如果用户关闭了他的标签页,或者去了另一个页面呢?在我的情况下,脚本继续工作。

当用户中止他的请求(关闭连接)时,node.js中有没有办法检查或检测或捕获事件?

I'm making some long polling with node.js.
Basically, node.js server accepts request from the user and then checks for some updates. If there're no updates, it will check them after the timeout.
But what if user has closed his tab, or went to another page? In my case, the script continues working.
Is there a way in node.js to check or detect or to catch an event when user has aborted his request (closed the connection)?

推荐答案

感谢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.

这篇关于如何检查在node.js服务器中是否中止连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆