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

我正在用node.js进行一些长的轮询。
基本上,node.js服务器接受来自用户的请求,然后检查一些更新。 如果没有更新,它会在超时后检查它们。
但是如果用户closures了他的标签,或者去了另一个页面呢? 在我的情况下,脚本继续工作。
有没有在node.js检查或检测或捕捉一个事件,当用户中止他的请求(closures连接)的方法?

感谢Miroshkoyojimbo87的回答,我能够赶上“近距离”的事件,但是我不得不做一些额外的调整。

刚刚捕捉“closures”事件的原因并不能解决我的问题,因为当客户端发送请求到node.js服务器时,如果连接仍然打开,服务器本身就不能获取信息,直到他发回一些东西客户端(据我所知 – 这是因为HTTP协议)。
所以,额外的调整是不时写回应答。
还有一件事是阻止这个工作,是我有“内容types”为“应用程序/ JSON”。 将其更改为“text / javascript”有助于在不closures连接的情况下不时传送“空白”。
最后,我有这样的事情:

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); 

我原来的代码要大得多,为了显示敏感部分,我不得不削减很多。

我想知道是否有更好的解决scheme,但目前这对我来说是有效的。

你需要使用req.on('close', function(err) { ... }); 而不是req.connection.on('close', function(err) { ... });

有一个非常重要的区别。 req.on()在req.connection.on()中为此请求添加侦听器,您将侦听器添加到客户端和服务器之间的(保持活动)连接。 如果使用req.connection.on(),则每次客户端重新使用连接时,都会向同一个连接添加一个侦听器。 当连接终止时,所有侦听器都被触发。

函数范围通常可以让你安全地避免这种搞砸你的服务器逻辑,但这是一件很危险的事情。 幸运的是,至lessNodeJS 0.10.26足够聪明,可以警告用户:

 (node) warning: possible EventEmitter memory leak detected. 11 listeners added. Use emitter.setMaxListeners() to increase limit. Trace: at Socket.EventEmitter.addListener (events.js:160:15) at Socket.Readable.on (_stream_readable.js:689:33) ... 

有没有在node.js检查或检测或捕捉一个事件,当用户中止他的请求(closures连接)的方法吗?

您可以尝试使用http.ServerRequestclosures事件 。 简单的例子:

 var http = require("http"), util = require("util"); var httpServer = http.createServer(function(req, res) { util.log("new request..."); // notify me when client connection is lost req.on("close", function(err) { util.log("request closed..."); }); // wait with response for 15 seconds setTimeout(function() { res.writeHead(200, {'Content-Type': 'text/plain'}); res.write("response"); res.end(); util.log("response sent..."); }, 15000); }); httpServer.listen(8080); util.log("Running on 8080"); 

似乎你的问题与这个非常相似:

NodeJS HTTP请求连接的closures事件触发两次

尝试

 request.connection.on('close', function () { ... }); 

我正在使用Express.js(〜4.10.6),下面的代码对我来说工作正常:

 //GET Request: app.get('/', function(req, res){ req.on('close', function(){ console.log('Client closed the connection'); }); }); 

只要closures浏览器的选项卡,浏览器就会closures连接,并按照预期执行callback函数。

Interesting Posts