0xff0000
0xff0000

Reputation: 917

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!

Upvotes: 7

Views: 7790

Answers (4)

andrewrk
andrewrk

Reputation: 31152

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"});
});

Upvotes: 1

yojimbo87
yojimbo87

Reputation: 68295

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.

Upvotes: 3

Alfred
Alfred

Reputation: 61771

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.

Upvotes: 2

generalhenry
generalhenry

Reputation: 17319

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.

Upvotes: 4

Related Questions