3

我正在尝试使用 NodeJS 实现长轮询技术。

我在服务器上部署了这个基本代码。

http = require('http');

function onRequest(request, response) {
    console.log('onRequest reached');
}

http.createServer(onRequest).listen(8080);
console.log('Server has started.');

当请求 localhost:8080 时,会触发 onRequest。当此连接处于活动状态时,我在第二个选项卡中请求同一页面,但不会触发 onRequest。但是,从另一个浏览器请求同一页面会触发 onRequest,而第一个连接仍然是“长轮询”。

浏览器有什么限制吗?这是如何以及为什么会发生的?如何避免这种情况?

顺便提一句。我正在尝试实现长轮询聊天和通知系统。实际上请求应该通过 AJAX 调用进行。

4

1 回答 1

3

可能是浏览器正在等待响应。立即尝试仅发送标头:

function onRequest(request, response) {
    response.writeHead(200, {'Content-Type': 'text/html'});
    console.log('onRequest reached');
}

另一个提示:如果您要使用长轮询,我建议您查看Server-Sent Events。对此有相当广泛的浏览器支持,并且还有一个适用于旧浏览器的polyfill。这是CoffeeScript 中的一个示例,展示了如何从 node.js 服务器发送事件。

于 2012-07-06T11:49:16.427 回答