SlideShare a Scribd company logo
2
Most read
3
Most read
4
Most read
Server Sent Events
Server-sent events (SSE) is a technology where a browser receives automat-
ic updates from a server via HTTP connection. The Server-Sent Events Event-
Source API is standardized as part of HTML5 by the W3C.
What is Server Sent Events ?
The WHATWG Web Applications 1.0 proposal included a mechanism to
push content to the client. On September 2006 ,1, the Opera web browser
implemented this new experimental technology in a feature called "Serv-
er-Sent Events"
History
it is is a community of people interested in evolving HTML and related tech-
nologies. The WHATWG was founded by individuals from Apple, the Mozilla
Foundation and Opera Software in 2004.
What is WHATWG ? (Web Hypertext Application Technology Working Group )
Server-sent events is a standard describing how servers can initiate data
transmission towards clients once an initial client connection has been
established. They are commonly used to send message updates or continu-
ous data streams to a browser client and designed to enhance native,
cross-browser streaming through a JavaScript API called EventSource,
through which a client requests a particular URL in order to receive an
event stream.
Overview
not all but most of the browsers support SSE, as the following list
internet explorer : NO!! i`m not Surprised !!
Mozilla Firefox : yes, with Firefox 6.0
Google Chrome : yes
Opera : yes, starting with opera 11
Safari : yes, starting with Safari 5.0
we can use the following code to check:
if(typeof(EventSource) !== "undefined") {
// Yes! Server-sent events support!
// Some code.....
} else {
// Sorry! No server-sent events support..
}
Does it supported in all browsers ?!
How to programmatically check ?!
what basicly need to do is to define a type of data and connection by
setting the following three headers using any programing language:
Then, we build the function to send a using event stream format
'Content-Type' : 'text/event-stream',
'Cache-Control' : 'no-cache',
'Connection' : 'keep-alive'
data: My messagenn
data: first linen
data: second linenn
how to use SSE with backend server ?
basicly a line that contains "data:", followed by your message, then nn
as the following:
What is event stream format ?
no problem, after eachline print n and after the last line print nn
as the following:
What if my data is multible lines ?
id: myUniqueIdn
data: my data linenn
You can send a unique id with an stream event by including a line starting
with "id:":
who can i give each event a unique ID?
data: {"msg": "First message"}nn
event: userlogonn
data: {"username": "John123"}nn
event: updaten
data: {"username": "John123", "emotion": "happy"}nn
source.addEventListener('message', function(e) {
var data = JSON.parse(e.data);
console.log(data.msg);
}, false);
source.addEventListener('userlogon', function(e) {
var data = JSON.parse(e.data);
console.log('User login:' + data.username);
}, false);
source.addEventListener('update', function(e) {
var data = JSON.parse(e.data);
console.log(data.username + ' is now ' + data.emotion);
}, false);
A single event source can generate different types events by including an
event name. If a line beginning with "event:" is present, followed by a
unique name for the event, the event is associated with that name. On the
client, an event listener can be setup to listen to that particular event.
For example, the following server output sends three types of events, a
generic 'message' event, 'userlogon', and 'update' event:
then adding event listeners on the client side script as the following:
can i Specifying an event name?
retry: 10000n
data: my data linenn
The browser attempts to reconnect to the source roughly 3 seconds after
each connection is closed. You can change that timeout by including a line
beginning with "retry:", followed by the number of milliseconds to wait
before trying to reconnect.
The following example attempts a reconnect after 10 seconds:
how to Control the Reconnection-timeout?
i have done a small server that creates two routes,
the first route is html page (front end page) listens to the second route
the Second route event stream page (Back end page) that send an event
stream containing the server memory usage and cpu usage every 1 second
the full code is on the next pages:
Do we have an example for nodeJS?
var express = require('express');
var app = express();
var fs = require('fs');
var sendInterval = 1000;
var os = require('os');
var osu = require('os-utils');
app.get('/', function(req, res){
res.write(fs.readFileSync(__dirname + '/index.html'));
res.end();
});
app.get('/talk', function(req, res){
res.writeHead(200, {
'Content-Type' : 'text/event-stream',
'Cache-Control' : 'no-cache',
'Connection' : 'keep-alive'
});
var sseId = (new Date()).toLocaleTimeString();
setInterval(function() {
osu.cpuUsage(function(v){
var data = JSON.stringify({
'freeMemory':parseInt(os.freemem()/1024/1024),
'usedMemory':parseInt((os.totalmem() - os.free-
mem())/1024/1024),
'totalMemory':parseInt(os.totalmem()/1024/1024),
'cpuUsage':parseInt(v*100)
});
res.write('id: first-event n');//handle event id here
res.write("data: " + data + 'nn');
});
}, sendInterval);
osu.cpuUsage(function(v){
var data = JSON.stringify({
'freeMemory':parseInt(os.freemem()/1024/1024),
'usedMemory':parseInt((os.totalmem() - os.free-
mem())/1024/1024),
'totalMemory':parseInt(os.totalmem()/1024/1024),
'cpuUsage':parseInt( v*100 )
});
res.write('id: first-event n');//handle event id here
res.write("data: " + data + 'nn');
});
});
app.listen(3000);
the back end page code:
var source = new EventSource('http://localhost:3000/talk');
source.addEventListener('open', function(event) {
//on open connection
}, false);
source.onmessage = function(event) {
console.log('onmessage event',event.data);
}
//then i implemented highcharts gauges for cpu and memory
the front end page code:

More Related Content

PDF
Server-Sent Events in Action
Andrei Rusu
 
PPT
Node js Modules and Event Emitters
TheCreativedev Blog
 
PPTX
Understanding REST APIs in 5 Simple Steps
Tessa Mero
 
PDF
Express node js
Yashprit Singh
 
PPT
Node.js Express Framework
TheCreativedev Blog
 
PPTX
NodeJS
Alok Guha
 
PDF
OWASP API Security Top 10 - API World
42Crunch
 
PDF
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 
Server-Sent Events in Action
Andrei Rusu
 
Node js Modules and Event Emitters
TheCreativedev Blog
 
Understanding REST APIs in 5 Simple Steps
Tessa Mero
 
Express node js
Yashprit Singh
 
Node.js Express Framework
TheCreativedev Blog
 
NodeJS
Alok Guha
 
OWASP API Security Top 10 - API World
42Crunch
 
Workshop 4: NodeJS. Express Framework & MongoDB.
Visual Engineering
 

What's hot (20)

DOCX
Api testing bible using postman
Abhishek Saxena
 
PDF
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
PPT
Postman.ppt
ParrotBAD
 
PPTX
Rest API
Rohana K Amarakoon
 
PPTX
Express js
Manav Prasad
 
PPTX
Node.js Express
Eyal Vardi
 
PDF
Nodejs presentation
Arvind Devaraj
 
PDF
Spring Framework - AOP
Dzmitry Naskou
 
PDF
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
HackIT Ukraine
 
PDF
Postman: An Introduction for Testers
Postman
 
PPTX
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
PPTX
Web api
Sudhakar Sharma
 
PPTX
Real-time ASP.NET with SignalR
Alexander Konduforov
 
PPTX
REST-API introduction for developers
Patrick Savalle
 
PPTX
An Introduction To REST API
Aniruddh Bhilvare
 
PDF
REST API and CRUD
Prem Sanil
 
PPTX
Automated Security Analysis of Android & iOS Applications with Mobile Securit...
Ajin Abraham
 
PPTX
Rest API Security
Stormpath
 
PPT
Jsp/Servlet
Sunil OS
 
PPTX
Spring boot
sdeeg
 
Api testing bible using postman
Abhishek Saxena
 
What is REST API? REST API Concepts and Examples | Edureka
Edureka!
 
Postman.ppt
ParrotBAD
 
Express js
Manav Prasad
 
Node.js Express
Eyal Vardi
 
Nodejs presentation
Arvind Devaraj
 
Spring Framework - AOP
Dzmitry Naskou
 
"15 Technique to Exploit File Upload Pages", Ebrahim Hegazy
HackIT Ukraine
 
Postman: An Introduction for Testers
Postman
 
Introduction to NodeJS
Cere Labs Pvt. Ltd
 
Real-time ASP.NET with SignalR
Alexander Konduforov
 
REST-API introduction for developers
Patrick Savalle
 
An Introduction To REST API
Aniruddh Bhilvare
 
REST API and CRUD
Prem Sanil
 
Automated Security Analysis of Android & iOS Applications with Mobile Securit...
Ajin Abraham
 
Rest API Security
Stormpath
 
Jsp/Servlet
Sunil OS
 
Spring boot
sdeeg
 
Ad

Similar to Server Sent Events (20)

PDF
ServerSentEvents.pdf
Alessandro Minoccheri
 
PDF
ServerSentEventsV2.pdf
Alessandro Minoccheri
 
PPTX
Fight empire-html5
Bhakti Mehta
 
PDF
Server-Sent Events (real-time HTTP push for HTML5 browsers)
yay w00t
 
PDF
HTML5 Server Sent Events/JSF JAX 2011 Conference
Roger Kitain
 
PPTX
Html5 server events
AbhishekMondal42
 
PPTX
Behind the scenes of Real-Time Notifications
Guillermo Mansilla
 
PDF
Server Side Events
thepilif
 
PPTX
Websocket vs SSE - Paris.js - 24/06/15
streamdata.io
 
PDF
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
PDF
Unlocking Realtime Web Applications - 4Developers Katowice 2023
Patryk Omiotek
 
PDF
Real-Time with Flowdock
Flowdock
 
PDF
What is a WebSocket? Real-Time Communication in Applications
Inexture Solutions
 
PDF
Server-Side Programming Primer
Ivano Malavolta
 
PDF
Comet with node.js and V8
amix3k
 
ODP
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
PDF
Role of Server-Sent Events in Reactive Programming
Covalensedigital
 
PPT
Get Real: Adventures in realtime web apps
daviddemello
 
PDF
Live Streaming & Server Sent Events
tkramar
 
PPT
Web-Socket
Pankaj Kumar Sharma
 
ServerSentEvents.pdf
Alessandro Minoccheri
 
ServerSentEventsV2.pdf
Alessandro Minoccheri
 
Fight empire-html5
Bhakti Mehta
 
Server-Sent Events (real-time HTTP push for HTML5 browsers)
yay w00t
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
Roger Kitain
 
Html5 server events
AbhishekMondal42
 
Behind the scenes of Real-Time Notifications
Guillermo Mansilla
 
Server Side Events
thepilif
 
Websocket vs SSE - Paris.js - 24/06/15
streamdata.io
 
Con fess 2013-sse-websockets-json-bhakti
Bhakti Mehta
 
Unlocking Realtime Web Applications - 4Developers Katowice 2023
Patryk Omiotek
 
Real-Time with Flowdock
Flowdock
 
What is a WebSocket? Real-Time Communication in Applications
Inexture Solutions
 
Server-Side Programming Primer
Ivano Malavolta
 
Comet with node.js and V8
amix3k
 
Server Sent Events, Async Servlet, Web Sockets and JSON; born to work together!
Masoud Kalali
 
Role of Server-Sent Events in Reactive Programming
Covalensedigital
 
Get Real: Adventures in realtime web apps
daviddemello
 
Live Streaming & Server Sent Events
tkramar
 
Ad

Recently uploaded (20)

PDF
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
PPTX
Presentation about variables and constant.pptx
kr2589474
 
PDF
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
PDF
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
PDF
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
PPTX
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
PPTX
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
PDF
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
PDF
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
PDF
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
PDF
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
PPTX
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
PPTX
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
PPTX
Explanation about Structures in C language.pptx
Veeral Rathod
 
PDF
Bandai Playdia The Book - David Glotz
BluePanther6
 
PPT
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
PDF
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
DOCX
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
PPTX
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
PPTX
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 
Generating Union types w/ Static Analysis
K. Matthew Dupree
 
Presentation about variables and constant.pptx
kr2589474
 
MiniTool Power Data Recovery Crack New Pre Activated Version Latest 2025
imang66g
 
Download iTop VPN Free 6.1.0.5882 Crack Full Activated Pre Latest 2025
imang66g
 
Adobe Illustrator Crack Full Download (Latest Version 2025) Pre-Activated
imang66g
 
classification of computer and basic part of digital computer
ravisinghrajpurohit3
 
Odoo Integration Services by Candidroot Solutions
CandidRoot Solutions Private Limited
 
Using licensed Data Loss Prevention (DLP) as a strategic proactive data secur...
Q-Advise
 
New Download FL Studio Crack Full Version [Latest 2025]
imang66g
 
Summary Of Odoo 18.1 to 18.4 : The Way For Odoo 19
CandidRoot Solutions Private Limited
 
vAdobe Premiere Pro 2025 (v25.2.3.004) Crack Pre-Activated Latest
imang66g
 
ConcordeApp: Engineering Global Impact & Unlocking Billions in Event ROI with AI
chastechaste14
 
AI-Ready Handoff: Auto-Summaries & Draft Emails from MQL to Slack in One Flow
bbedford2
 
Explanation about Structures in C language.pptx
Veeral Rathod
 
Bandai Playdia The Book - David Glotz
BluePanther6
 
Why Reliable Server Maintenance Service in New York is Crucial for Your Business
Sam Vohra
 
New Download MiniTool Partition Wizard Crack Latest Version 2025
imang66g
 
Can You Build Dashboards Using Open Source Visualization Tool.docx
Varsha Nayak
 
Visualising Data with Scatterplots in IBM SPSS Statistics.pptx
Version 1 Analytics
 
ASSIGNMENT_1[1][1][1][1][1] (1) variables.pptx
kr2589474
 

Server Sent Events

  • 2. Server-sent events (SSE) is a technology where a browser receives automat- ic updates from a server via HTTP connection. The Server-Sent Events Event- Source API is standardized as part of HTML5 by the W3C. What is Server Sent Events ? The WHATWG Web Applications 1.0 proposal included a mechanism to push content to the client. On September 2006 ,1, the Opera web browser implemented this new experimental technology in a feature called "Serv- er-Sent Events" History it is is a community of people interested in evolving HTML and related tech- nologies. The WHATWG was founded by individuals from Apple, the Mozilla Foundation and Opera Software in 2004. What is WHATWG ? (Web Hypertext Application Technology Working Group ) Server-sent events is a standard describing how servers can initiate data transmission towards clients once an initial client connection has been established. They are commonly used to send message updates or continu- ous data streams to a browser client and designed to enhance native, cross-browser streaming through a JavaScript API called EventSource, through which a client requests a particular URL in order to receive an event stream. Overview
  • 3. not all but most of the browsers support SSE, as the following list internet explorer : NO!! i`m not Surprised !! Mozilla Firefox : yes, with Firefox 6.0 Google Chrome : yes Opera : yes, starting with opera 11 Safari : yes, starting with Safari 5.0 we can use the following code to check: if(typeof(EventSource) !== "undefined") { // Yes! Server-sent events support! // Some code..... } else { // Sorry! No server-sent events support.. } Does it supported in all browsers ?! How to programmatically check ?!
  • 4. what basicly need to do is to define a type of data and connection by setting the following three headers using any programing language: Then, we build the function to send a using event stream format 'Content-Type' : 'text/event-stream', 'Cache-Control' : 'no-cache', 'Connection' : 'keep-alive' data: My messagenn data: first linen data: second linenn how to use SSE with backend server ? basicly a line that contains "data:", followed by your message, then nn as the following: What is event stream format ? no problem, after eachline print n and after the last line print nn as the following: What if my data is multible lines ? id: myUniqueIdn data: my data linenn You can send a unique id with an stream event by including a line starting with "id:": who can i give each event a unique ID?
  • 5. data: {"msg": "First message"}nn event: userlogonn data: {"username": "John123"}nn event: updaten data: {"username": "John123", "emotion": "happy"}nn source.addEventListener('message', function(e) { var data = JSON.parse(e.data); console.log(data.msg); }, false); source.addEventListener('userlogon', function(e) { var data = JSON.parse(e.data); console.log('User login:' + data.username); }, false); source.addEventListener('update', function(e) { var data = JSON.parse(e.data); console.log(data.username + ' is now ' + data.emotion); }, false); A single event source can generate different types events by including an event name. If a line beginning with "event:" is present, followed by a unique name for the event, the event is associated with that name. On the client, an event listener can be setup to listen to that particular event. For example, the following server output sends three types of events, a generic 'message' event, 'userlogon', and 'update' event: then adding event listeners on the client side script as the following: can i Specifying an event name?
  • 6. retry: 10000n data: my data linenn The browser attempts to reconnect to the source roughly 3 seconds after each connection is closed. You can change that timeout by including a line beginning with "retry:", followed by the number of milliseconds to wait before trying to reconnect. The following example attempts a reconnect after 10 seconds: how to Control the Reconnection-timeout? i have done a small server that creates two routes, the first route is html page (front end page) listens to the second route the Second route event stream page (Back end page) that send an event stream containing the server memory usage and cpu usage every 1 second the full code is on the next pages: Do we have an example for nodeJS?
  • 7. var express = require('express'); var app = express(); var fs = require('fs'); var sendInterval = 1000; var os = require('os'); var osu = require('os-utils'); app.get('/', function(req, res){ res.write(fs.readFileSync(__dirname + '/index.html')); res.end(); }); app.get('/talk', function(req, res){ res.writeHead(200, { 'Content-Type' : 'text/event-stream', 'Cache-Control' : 'no-cache', 'Connection' : 'keep-alive' }); var sseId = (new Date()).toLocaleTimeString(); setInterval(function() { osu.cpuUsage(function(v){ var data = JSON.stringify({ 'freeMemory':parseInt(os.freemem()/1024/1024), 'usedMemory':parseInt((os.totalmem() - os.free- mem())/1024/1024), 'totalMemory':parseInt(os.totalmem()/1024/1024), 'cpuUsage':parseInt(v*100) }); res.write('id: first-event n');//handle event id here res.write("data: " + data + 'nn'); }); }, sendInterval); osu.cpuUsage(function(v){ var data = JSON.stringify({ 'freeMemory':parseInt(os.freemem()/1024/1024), 'usedMemory':parseInt((os.totalmem() - os.free- mem())/1024/1024), 'totalMemory':parseInt(os.totalmem()/1024/1024), 'cpuUsage':parseInt( v*100 ) }); res.write('id: first-event n');//handle event id here res.write("data: " + data + 'nn'); }); }); app.listen(3000); the back end page code:
  • 8. var source = new EventSource('http://localhost:3000/talk'); source.addEventListener('open', function(event) { //on open connection }, false); source.onmessage = function(event) { console.log('onmessage event',event.data); } //then i implemented highcharts gauges for cpu and memory the front end page code: