7
votes

I'm actually trying to create a web-application which will utilizes the Server-Sent Events draft. From my knowledge, SSEs utilize one thread per connection, and since the server is going to continuously pump data to the client, without being idle even for a second, there's no way I'll be able to put the thread back in the pool.

Hence I'm trying to use Node.JS (which I haven't used till date) to handle connections to the server. I've been through the HTML5 Rocks introduction to SSE and there is a code sample integrating SSEs with Node.JS.

However, I'm confused as to whether Node.JS will handle the thousands of client connections concurrently and utilize the server more efficiently than an Apache server? Can anyone help me understand how exactly Node will act here?

Sorry if I sound a bit too vague. I'm ready to make as many clarifications as possible! Thanks!

4
if you haven't, watch this intro video (yes it's long, but it's good) yuiblog.com/blog/2010/05/20/video-dahlgeneralhenry
you know that IE and FF are a no-go for this method right?Billy Moon
@generalhenry - Thanks for the link. Will check it out.0xff0000
@billy-moon - Yes, I'm thinking of resorting to Node.JS + Socket.Io for browsers other than Chrome and Safari.0xff0000

4 Answers

4
votes

php:

do {
  sendMsg($startedAt , time());
  sleep(5);
} while(true);

vs

node.js

setInterval(function() {
  constructSSE(res, id, (new Date()).toLocaleTimeString());
}, 5000);

The difference it the sleep blocks the php thread 5 seconds. During those 5 seconds the server needs to have a dedicated thread doing absolutely nothing. One thread per user.

With the node.js version the setInterval doesn't block the thread. The one node.js thread can handle all the users.

3
votes

Try to look at Understanding the node.js event loop article regarding concurrent connections. I would recommend to create a web application which utilizes WebSockets rather then Server-sent events because SSEs are less supported by browsers than WebSockets. Also there are lots of WebSockets based node.js modules with source codes at GitHub which can "inspire" you.

2
votes

However, I'm confused as to whether Node.JS will handle the thousands of client connections concurrently and utilize the server more efficiently than an Apache server? Can anyone help me understand how exactly Node will act here?

I think you should read Understanding event loops and writing great code for Node.js to get a better grasp about the event-loop. In node.js nothing is blocking which will save you tons of CPU-cycles.

Also TJ's ebook can help you grasp events. When something happens your callback associated with that event will be called.

1
votes

Try using express + connect-sse:

var sse, express, app;

sse = require('connect-sse')();
express = require('express')

app = express()
app.get('/events', sse, function (req, res) {
  res.json("this is an event");
  res.json({here: "is", another: "event"});
});