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: