node.js-将数据推送到客户端-只能连接一个客户端? [英] node.js - push data to client - only one client can be connected?

查看:94
本文介绍了node.js-将数据推送到客户端-只能连接一个客户端?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建一个服务器端解决方案,该解决方案会通过node.js定期将数据推送到客户端(无客户端轮询)。连接应该永久打开,并且只要服务器有新数据,它就会将其推送到客户端。



这是我简单的示例脚本:

  var sys = require('sys'),
http = require('http');
http.createServer(函数(req,res){
res.writeHead(200,{'Content-Type':'text / html'});
sys.puts('Start正在发送...');

setInterval(function(){
res.write(< script type ='text / javascript'> document.write('test< br> ;')< / script>);
},10000);
})。listen(8010);

这基本上是可行的,但似乎一次只能连接一个客户端。



如果使用浏览器打开 http://127.0.0.1:8010/ ,我每隔10秒就会看到新的输出。但是,当我打开另一个具有相同网址的标签时,它将永远加载。只有关闭第一个选项卡,我才能从服务器获得同意。



我需要做什么才能为多个客户端提供服务?

解决方案

这绝对是一个错误,由于 keep-alive 以及HTTP / 1.1和Node损坏,浏览器重新使用了相同的连接。



您可以在Opera11中看到它,打开页面两次,使用完全相同的连接打开完全相同的页面。



卷曲和所有未设置 Connection:keep-alive 的东西都很好,但是浏览器无法两次打开同一页面。尽管您可以打开'localhost:8010'和'localhost:8010 / foo',并且它们在两个页面上都可以使用。



注意:仅影响 GET 请求, POST 请求工作得很好,因为没有重复使用连接。



我已经提交了问题


I am trying to create a server-side solution which periodically pushes data to the client (no client-side polling) via node.js. The connection should be open permanently and whenever the server has new data, it pushes it down to the client.

Here is my simple sample script:

var sys = require('sys'),
http = require('http');
http.createServer(function (req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
    sys.puts('Start sending...');

    setInterval(function(){
        res.write("<script type='text/javascript'>document.write('test<br>')</script>");
    }, 10000);
}).listen(8010);

This basically works, but it seems that only one client at a time can be connected.

If I open http://127.0.0.1:8010/ with my browser I see every 10 seconds the new output written. But when I open another tab with the same url, it just loads forever. Only if I close the first tab, I get conent from the server.

What do I need to do in order to server multiple clients?

解决方案

This is definitely a bug, what happens is that the Browser re-uses the same connection due to keep-alive and HTTP/1.1 and Node screws up.

You can see this at work in Opera11, open the page twice, it's the exact same page, using the exact same connection.

Curl and everything that doesn't set Connection: keep-alive works just fine, but Browsers fail to open the same page twice. Although you can open 'localhost:8010' and 'localhost:8010/foo' and it will work on both pages.

Note: This only affects GET requests, POST requests work just fine since there's no re-using of the connection.

I've filed an issue on this.

这篇关于node.js-将数据推送到客户端-只能连接一个客户端?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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