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

PPTX
Angular 9
PPTX
Angular tutorial
PPTX
Angular
PDF
World of CSS Grid
PDF
HTML5--The 30,000' View (A fast-paced overview of HTML5)
PDF
Angular 10 course_content
PDF
Spring security oauth2
PPTX
Java script form validation
Angular 9
Angular tutorial
Angular
World of CSS Grid
HTML5--The 30,000' View (A fast-paced overview of HTML5)
Angular 10 course_content
Spring security oauth2
Java script form validation

What's hot (20)

PPTX
Android pentesting the hackers-meetup
PPT
Asp.net server controls
PPTX
Unirest Java Tutorial | Java Http Client
PDF
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
PPT
Web Technology - PHP Arrays
PPTX
Study of software ware and hardware requirements.
PPTX
Node js introduction
PDF
Spring Framework - Spring Security
PDF
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
PPTX
Introduction to asp.net
PPT
Asp.net basic
PPTX
Build RESTful API Using Express JS
PPTX
Introduction to HTML, CSS, and JavaScript for Web Development
ODP
Protocol Buffers
PPT
Diziler C#
PPTX
Chapter 3 servlet & jsp
PDF
Angular Best Practices - Perfomatix
PDF
PPTX
Android pentesting the hackers-meetup
Asp.net server controls
Unirest Java Tutorial | Java Http Client
Angular Directives | Angular 2 Custom Directives | Angular Tutorial | Angular...
Web Technology - PHP Arrays
Study of software ware and hardware requirements.
Node js introduction
Spring Framework - Spring Security
Fuzzing malware for fun & profit. Applying Coverage-Guided Fuzzing to Find Bu...
Introduction to asp.net
Asp.net basic
Build RESTful API Using Express JS
Introduction to HTML, CSS, and JavaScript for Web Development
Protocol Buffers
Diziler C#
Chapter 3 servlet & jsp
Angular Best Practices - Perfomatix
Ad

Similar to Server Sent Events (20)

PPTX
Html5 server events
PDF
Server-Sent Events in Action
PDF
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
PPT
Web Services
 
PPTX
Behind the scenes of Real-Time Notifications
PPTX
Fight empire-html5
KEY
Message in a Bottle
PDF
How a network connection is created A network connection is initi.pdf
PDF
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
PPTX
Web application development ( basics )
PPTX
PPT-1_19BCS1566.pptx presentation education
PPSX
13 asp.net session19
PPTX
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
PDF
Event Source On Labs
DOCX
Web services Concepts
PPT
21. Application Development and Administration in DBMS
PDF
MongoDB.local Berlin: App development in a Serverless World
PPTX
Introduction about-ajax-framework
PPTX
Real time Communication with Signalr (Android Client)
PPT
Asynchronous Mobile Web Services:
Html5 server events
Server-Sent Events in Action
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Web Services
 
Behind the scenes of Real-Time Notifications
Fight empire-html5
Message in a Bottle
How a network connection is created A network connection is initi.pdf
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
Web application development ( basics )
PPT-1_19BCS1566.pptx presentation education
13 asp.net session19
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
Event Source On Labs
Web services Concepts
21. Application Development and Administration in DBMS
MongoDB.local Berlin: App development in a Serverless World
Introduction about-ajax-framework
Real time Communication with Signalr (Android Client)
Asynchronous Mobile Web Services:
Ad

Recently uploaded (20)

PPTX
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
PDF
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
PDF
Salesforce Agentforce AI Implementation.pdf
PDF
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
DOCX
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
PPTX
Oracle Fusion HCM Cloud Demo for Beginners
PPTX
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
PPTX
Advanced SystemCare Ultimate Crack + Portable (2025)
PDF
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
PPTX
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
PDF
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
PPTX
Tech Workshop Escape Room Tech Workshop
PPTX
Weekly report ppt - harsh dattuprasad patel.pptx
PDF
Time Tracking Features That Teams and Organizations Actually Need
PPTX
Custom Software Development Services.pptx.pptx
PDF
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
PDF
Topaz Photo AI Crack New Download (Latest 2025)
PDF
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
PDF
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
PDF
Digital Systems & Binary Numbers (comprehensive )
AMADEUS TRAVEL AGENT SOFTWARE | AMADEUS TICKETING SYSTEM
How to Make Money in the Metaverse_ Top Strategies for Beginners.pdf
Salesforce Agentforce AI Implementation.pdf
How AI/LLM recommend to you ? GDG meetup 16 Aug by Fariman Guliev
Greta — No-Code AI for Building Full-Stack Web & Mobile Apps
Oracle Fusion HCM Cloud Demo for Beginners
Log360_SIEM_Solutions Overview PPT_Feb 2020.pptx
Advanced SystemCare Ultimate Crack + Portable (2025)
Product Update: Alluxio AI 3.7 Now with Sub-Millisecond Latency
WiFi Honeypot Detecscfddssdffsedfseztor.pptx
EaseUS PDF Editor Pro 6.2.0.2 Crack with License Key 2025
Tech Workshop Escape Room Tech Workshop
Weekly report ppt - harsh dattuprasad patel.pptx
Time Tracking Features That Teams and Organizations Actually Need
Custom Software Development Services.pptx.pptx
Top 10 Software Development Trends to Watch in 2025 🚀.pdf
Topaz Photo AI Crack New Download (Latest 2025)
AI/ML Infra Meetup | Beyond S3's Basics: Architecting for AI-Native Data Access
AI/ML Infra Meetup | LLM Agents and Implementation Challenges
Digital Systems & Binary Numbers (comprehensive )

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: