HTML5 and CSS3, Second Edition

(singke) #1
To demonstrate this we’ll set up a very basic page that will display messages
from our server. The web server available in the book’s example code already
has support for SSE, so we’ll focus on the client-side implementation. Create
a simple HTML page like this, with a place for the messages to display:

where_next/html5_sse/index.html
<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8">
<title>AwesomeCoMessages</title>
<linkrel="stylesheet"href="stylesheets/style.css">
</head>
<body>
<h2>AwesomeCoMessages</h2>
<divid="message">connecting....</div>
<scriptsrc='javascripts/streamer.js'></script>
</body>
</html>

We’ll also need a place to put our JavaScript code. Create the file
javascripts/streamer.js and link it to the HTML file:

where_next/html5_sse/index.html
<scriptsrc='javascripts/streamer.js'></script>

Now let’s get some data displaying on this page.


Listening for Events


In javascripts/streamer.js, we’ll create a function called createMessageListeners(), which
will define all of the event listeners for server-sent events and will establish
the connection to the server’s event stream.

where_next/html5_sse/javascripts/streamer.js
varcreateMessageListeners=function(){
varmessageSource=newEventSource("/stream");
}

We use the EventSource object to create the connection to the event stream.
Depending on the web browser, this source may need to be on the same
server as the web page because of the same-origin policy restrictions. CORS
support for SSE is not widespread yet.

createMessageListeners();

Once we establish a connection, the server sends out a continuous stream
of messages. The simplest message looks like this:

data:We are bringingevenmoreawesomeness to you!

Chapter 11. Where to Go Next • 248


Download from Wow! eBook <www.wowebook.com> report erratum • discuss

Free download pdf