node.js - push data to client - only one client can be connected?

不问归期 提交于 2019-12-11 03:22:42

问题


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?


回答1:


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.




回答2:


You should use socket.io. It handles all the heavy lifting for you and is a really cool library.




回答3:


Be careful with this!

node.js is non-blocking but at the same time handles only 1 connection at a time. What you did is put the node into a dead state, that's why you see data on the second client when you close the first.



来源:https://stackoverflow.com/questions/4360970/node-js-push-data-to-client-only-one-client-can-be-connected

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!