Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Server-Sent Events on Node.JS

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!

like image 681
0xff0000 Avatar asked Mar 24 '11 04:03

0xff0000


2 Answers

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.

like image 148
generalhenry Avatar answered Sep 22 '22 08:09

generalhenry


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.

like image 29
yojimbo87 Avatar answered Sep 20 '22 08:09

yojimbo87