SSE (Server sent events) using nodeJs and Angular2

We are on git also : 

We use http protocol for client server communication. We just request the http server through different http methods like : get , post and thus fetch the response from the server. But http connection is stateless in nature. Once we make request and server acknowledges us with the response , our connection closes. It is good for simple website where we simply need to populate our browser from the server response. But suppose, if  we need the live data (Real time data)

example 1 : Cricket score. We need a webpage where the score of players gets updated regularly with update in database server.

example 2 : Webpage for stock trading , where the share rates of different companies changes within milliseconds.

All these webpages need frequent updates from the web server. To create this type of application we have following techniques with us :

a)Continuous pooling the server with http request. So here we will continuously request the server with interval of few seconds. Through this approach we will achieve our aim but it is very bad practice. Here we are continuously opening and closing the connection.

getRecords(){

setInterval(function(){

this.http.get("url").subscribe(

(res : Response)=>{

this.record = res.json();

},

(error)=>{

console.log('The error is ",error);

})

},1000);

}

b) In this approach , a connection is opened between the client and the server. Through this opened connection , our server regularly sends data to the browser. As, the connection is opened in SSE , so server can send any data anytime. This type of approach creates a real time presentation over the browser.

Let’s create a small application on this. In this application server will send current milliseconds stamp to the client browser with interval of 1 second.

Create nodejs programme :

var express = require('express');
var app = express();

var route = express.Router();

var connections = [];
route.get('/data', function (req, res) {
req.socket.setTimeout(50000000);
res.writeHead(200, {
'Content-Type':'text/event-stream',
'Cache-Control':'no-cache',
'Connection':'keep-alive'
})
res.write('/n');
connections.push(res)


req.on("close", function () {
var rem=0;
for (let i=0; i<connections.length; i++) {
if (connections[i] ==res) {
rem=i;
break;
}
}
connections.splice(rem, 1)

});


})

setInterval(function () {
connections.forEach(function (res) {
var d=new Date();
res.write(`data: ${d.getMilliseconds()}\n\n`);
})
}, 1000);
app.use('/api', route)
app.listen(3002, function () {
console.log("Listening on port 3004")
})

From server we are regularly pushing the data to the browser. So on the client side , we need to capture all those data. For this we need to create the observable. Because observable is a stream through which more then 1 events can be passed. Now let us create a .ts file .

 

import { Component, OnInit, NgZone } from '@angular/core';
import { Observable } from 'rxjs/Observable'
import { Http, Response } from '@angular/http';
@Component({
selector:'app-sse',
templateUrl:'./sse.component.html',
styleUrls: ['./sse.component.css']
})
export class SseComponent implements OnInit {
private sse : any;
private record:Observable<any>;
constructor(private zone:NgZone) {
var EventSource=window['EventSource'];
this.sse=new EventSource('http://localhost:3002/api/data');
}

ngOnInit() {
this.record=this.getMessages();
}

getMessages():Observable<any> {
return new Observable<any>(observer=> {

this.sse.onmessage=evt=> {
this.zone.run(() =>observer.next(evt.data));
};
return () =>this.sse.close();
});

}
}

Our html file is :

Current Millisecond is {{record | async}}

Output :

Current Millisecond is 809

Some of advantages of SSE :

1)We can have live data through this.

2)Stock ticker streaming

3)twitter feed updating

4)Notifications to browser

5)Transported over simple http protocol

6)Built in support for re-connection and event-id

7)Can be poly-filled with javascript to support all odd browsers , which does not support SSE

Disadvantages of SSE :

1)No binary support

2)Maximum connection limit

According to the survey of caniuse.com

  • 90% of global users use socket programming for live data
  • 84% of global users natively support SSE for live dataB

By Pankaj Kumar Agarwal

Leave a reply:

Site Footer