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

查看:45
本文介绍了如何检查 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)?

推荐答案

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

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

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