开发者

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

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/ja开发者_开发百科vascript'>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.


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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜