HTML5 and CSS3, Second Edition

(singke) #1
That’s the word data, followed by a colon, followed by the message text, followed
by a blank line—not just a newline character, but a complete blank line. A
message like this:

data:We are bringingevenmoreawesomeness to you!
data:Are you readyto be evenmoreawesome?

is a single message with multiple lines. A message like this:


data:We are bringingevenmoreawesomeness to you!

data:Are you readyto be evenmoreawesome?

is considered two separate messages. You can send plain text, or you can
construct JSON, which you could parse on the client. The protocol is really,
really simple but very powerful. The server just keeps on sending messages
to all connected clients until it stops or the clients disconnect.

To grab a message, we respond to the message event of EventSource and grab the
message from event.data, like this:

where_next/html5_sse/javascripts/streamer.js
messageSource.addEventListener("message", function(event){
document.getElementById("message").innerHTML= event.data;
}, false);

That’s all it takes. Most of the hard work comes from creating the server and
figuring out what you want to do with the messages once you have them.

You can listen to other events, like close, open, or even your own custom events.
If the server sends a message like this:

event:stockupdate
data:{"stock":"MSFT","value":"34.01"}

on the client, you’d listen for stockupdate events instead of message events, and
parse the data out. You can even tell the client how long it should wait to
retry by sending this message from the server:

retry: 10000

This will make the client wait ten seconds between requests instead of its
default three seconds.

You can make this work in older browsers that don’t support Server-Sent
Events. Use Modernizr to detect support and load a simple EventSource
polyfill^5 when needed.


  1. https://github.com/remy/polyfills/blob/master/EventSource.js


report erratum • discuss

Server-Sent Events • 249


Download from Wow! eBook <www.wowebook.com>

Free download pdf