SlideShare a Scribd company logo
1 of 8
Download to read offline
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

What's hot

Angular tutorial
Angular tutorialAngular tutorial
Angular tutorialRohit Gupta
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMMudasir Qazi
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Previewvaluebound
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjsmanojbkalla
 
Mobile Application Development With Android
Mobile Application Development With AndroidMobile Application Development With Android
Mobile Application Development With Androidguest213e237
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react formYao Nien Chung
 
Git basics to advance with diagrams
Git basics to advance with diagramsGit basics to advance with diagrams
Git basics to advance with diagramsDilum Navanjana
 
Angular data binding
Angular data binding Angular data binding
Angular data binding Sultan Ahmed
 
Android installation
Android installationAndroid installation
Android installationDurai S
 
Git flow Introduction
Git flow IntroductionGit flow Introduction
Git flow IntroductionDavid Paluy
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Androidma-polimi
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScriptAhmed El-Kady
 

What's hot (20)

Introduction to Angularjs
Introduction to AngularjsIntroduction to Angularjs
Introduction to Angularjs
 
Git github
Git githubGit github
Git github
 
Angular tutorial
Angular tutorialAngular tutorial
Angular tutorial
 
Design Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVMDesign Pattern - MVC, MVP and MVVM
Design Pattern - MVC, MVP and MVVM
 
React JS: A Secret Preview
React JS: A Secret PreviewReact JS: A Secret Preview
React JS: A Secret Preview
 
Typescript ppt
Typescript pptTypescript ppt
Typescript ppt
 
What is component in reactjs
What is component in reactjsWhat is component in reactjs
What is component in reactjs
 
Vue.js
Vue.jsVue.js
Vue.js
 
Mobile Application Development With Android
Mobile Application Development With AndroidMobile Application Development With Android
Mobile Application Development With Android
 
Lets make a better react form
Lets make a better react formLets make a better react form
Lets make a better react form
 
jQuery
jQueryjQuery
jQuery
 
Vue js for beginner
Vue js for beginner Vue js for beginner
Vue js for beginner
 
Introduction git
Introduction gitIntroduction git
Introduction git
 
Git basics to advance with diagrams
Git basics to advance with diagramsGit basics to advance with diagrams
Git basics to advance with diagrams
 
Angular data binding
Angular data binding Angular data binding
Angular data binding
 
Android installation
Android installationAndroid installation
Android installation
 
Git flow Introduction
Git flow IntroductionGit flow Introduction
Git flow Introduction
 
React js
React jsReact js
React js
 
Intents in Android
Intents in AndroidIntents in Android
Intents in Android
 
Angular 4 and TypeScript
Angular 4 and TypeScriptAngular 4 and TypeScript
Angular 4 and TypeScript
 

Similar to Server Sent Events

Server-Sent Events in Action
Server-Sent Events in ActionServer-Sent Events in Action
Server-Sent Events in ActionAndrei Rusu
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha
 
Web Services
Web ServicesWeb Services
Web ServicesF K
 
Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsGuillermo Mansilla
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5Bhakti Mehta
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a BottleZohar Arad
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfarccreation001
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...PROIDEA
 
Web application development ( basics )
Web application development ( basics )Web application development ( basics )
Web application development ( basics )Chirag Nag
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19Vivek chan
 
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)Lucas Jellema
 
Web services Concepts
Web services ConceptsWeb services Concepts
Web services Conceptspasam suresh
 
21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMS21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMSkoolkampus
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-frameworkSakthi Bro
 
Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Deepak Gupta
 
Asynchronous Mobile Web Services:
Asynchronous Mobile Web Services: Asynchronous Mobile Web Services:
Asynchronous Mobile Web Services: Dr. Fahad Aijaz
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 ConferenceRoger Kitain
 

Similar to Server Sent Events (20)

Html5 server events
Html5 server eventsHtml5 server events
Html5 server events
 
Server-Sent Events in Action
Server-Sent Events in ActionServer-Sent Events in Action
Server-Sent Events in Action
 
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
Sencha Roadshow 2017: Build Progressive Web Apps with Ext JS and Cmd
 
Web Services
Web ServicesWeb Services
Web Services
 
Behind the scenes of Real-Time Notifications
Behind the scenes of Real-Time NotificationsBehind the scenes of Real-Time Notifications
Behind the scenes of Real-Time Notifications
 
Fight empire-html5
Fight empire-html5Fight empire-html5
Fight empire-html5
 
Message in a Bottle
Message in a BottleMessage in a Bottle
Message in a Bottle
 
How a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdfHow a network connection is created A network connection is initi.pdf
How a network connection is created A network connection is initi.pdf
 
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
4Developers 2018: Real-time capabilities in ASP.NET Core web applications (To...
 
Web application development ( basics )
Web application development ( basics )Web application development ( basics )
Web application development ( basics )
 
13 asp.net session19
13 asp.net session1913 asp.net session19
13 asp.net session19
 
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
Don't call us - we'll push - cross tier push architecture (JavaOne 2011)
 
Event Source On Labs
Event Source On LabsEvent Source On Labs
Event Source On Labs
 
Web services Concepts
Web services ConceptsWeb services Concepts
Web services Concepts
 
21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMS21. Application Development and Administration in DBMS
21. Application Development and Administration in DBMS
 
MongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless WorldMongoDB.local Berlin: App development in a Serverless World
MongoDB.local Berlin: App development in a Serverless World
 
Introduction about-ajax-framework
Introduction about-ajax-frameworkIntroduction about-ajax-framework
Introduction about-ajax-framework
 
Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)Real time Communication with Signalr (Android Client)
Real time Communication with Signalr (Android Client)
 
Asynchronous Mobile Web Services:
Asynchronous Mobile Web Services: Asynchronous Mobile Web Services:
Asynchronous Mobile Web Services:
 
HTML5 Server Sent Events/JSF JAX 2011 Conference
HTML5 Server Sent Events/JSF  JAX 2011 ConferenceHTML5 Server Sent Events/JSF  JAX 2011 Conference
HTML5 Server Sent Events/JSF JAX 2011 Conference
 

Recently uploaded

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...MyIntelliSource, Inc.
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaHanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...stazi3110
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfAlina Yurenko
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesPhilip Schwarz
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfPower Karaoke
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxnada99848
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样umasea
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...OnePlan Solutions
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureDinusha Kumarasiri
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEEVICTOR MAESTRE RAMIREZ
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Andreas Granig
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...Christina Lin
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWave PLM
 

Recently uploaded (20)

Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
Steps To Getting Up And Running Quickly With MyTimeClock Employee Scheduling ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort ServiceHot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
Hot Sexy call girls in Patel Nagar🔝 9953056974 🔝 escort Service
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
React Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief UtamaReact Server Component in Next.js by Hanief Utama
React Server Component in Next.js by Hanief Utama
 
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
Building a General PDE Solving Framework with Symbolic-Numeric Scientific Mac...
 
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdfGOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
GOING AOT WITH GRAALVM – DEVOXX GREECE.pdf
 
Folding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a seriesFolding Cheat Sheet #4 - fourth in a series
Folding Cheat Sheet #4 - fourth in a series
 
The Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdfThe Evolution of Karaoke From Analog to App.pdf
The Evolution of Karaoke From Analog to App.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
software engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptxsoftware engineering Chapter 5 System modeling.pptx
software engineering Chapter 5 System modeling.pptx
 
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
办理学位证(UQ文凭证书)昆士兰大学毕业证成绩单原版一模一样
 
Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...Advancing Engineering with AI through the Next Generation of Strategic Projec...
Advancing Engineering with AI through the Next Generation of Strategic Projec...
 
Implementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with AzureImplementing Zero Trust strategy with Azure
Implementing Zero Trust strategy with Azure
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
Cloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEECloud Data Center Network Construction - IEEE
Cloud Data Center Network Construction - IEEE
 
Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024Automate your Kamailio Test Calls - Kamailio World 2024
Automate your Kamailio Test Calls - Kamailio World 2024
 
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
ODSC - Batch to Stream workshop - integration of Apache Spark, Cassandra, Pos...
 
What is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need ItWhat is Fashion PLM and Why Do You Need It
What is Fashion PLM and Why Do You Need It
 

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: