• No se han encontrado resultados

Aspectos éticos

In document FACULTAD DE CIENCIAS DE LA COMUNICACIÓN (página 35-43)

To build a functional example application, you’ll need a server resource that can send the events in the expected format and can also serve the client that will subscribe to the event stream. As mentioned, you could use any language to build this server resource, but to stay consistent with the other examples in the book, use JavaScript. You’re probably used to using JavaScript in the browser. You can also use it on a server, just like any other scripting engine. The most popular implementation of JavaScript as a standalone scripting engine is the Node.js framework, which has been ported to multiple operating systems. The Node.

js framework provides a fast JavaScript interpreter and a framework of APIs for accessing the filesystem, network stack, and other resources on the server.

Tip If you’ve never used Node.js, you can learn more about it at http://nodejs.org

.

To run this example, you’ll need a server with Node.js installed. You’ll build a simple script that will both act as the event streamer and serve the event client. As you can see in Listing 3-5, it’s quite easy to build a simple HTTP server with Node.js.

Listing 3-5. A Simple Event Stream Server Written in JavaScript // Include the modules needed to build the server.

var http = require('http');

var sys = require('sys');

var fs = require('fs');

// Use the http.createServer method to create a server listening on port 8030.

// The server will call the handleRequest method each time a request is // received.

http.createServer(handleRequest).listen(8030);

/**

* Handle an incoming request from the server.

* @param {Object} request The request headers.

* @param {Object} resource A reference to the server resource that received * the request.

*/

function handleRequest(request, resource) {

// Incoming requests to our server will be to one of two URLs.

// If the request is for /example3-5-events we should send our SSE.

// If the request is for /example3-5.html, we should serve the example client.

if (request.url == '/example3-5-events') { // Initialize an event stream.

sendSSE(request, resource);

} else if (request.url == '/example3-6.html'){

// Send the client.

resource.writeHead(200, {'Content-Type': 'text/html'});

resource.write(fs.readFileSync('example3-6.html'));

resource.end();

} } /**

* Initializes an event stream and starts sending an event every 5 seconds.

* @param {Object} request * @param {Object} resource */

function sendSSE(request, resource) { // Initialize the event stream.

resource.writeHead(200, {

'Content-Type': 'text/event-stream', 'Cache-Control': 'no-cache',

'Connection': 'keep-alive' });

// Send an event every 5 seconds.

setInterval(function() {

// Randomly generate either 0 or 1.

var randNumber = Math.floor(Math.random() * 2);

// If the random number is 1, set isChanged to true. Otherwise, set it to // false.

var isChanged = (randNumber === 1) ? true : false;

resource.write('data: ' + '{"isChanged":' + isChanged + '}\n\n');

}, 5000);

}

If you request example3-6.html it will serve the HTML client (which you’ll define in Listing 3-6), and if you request example3-5-events it will initiate an event stream that will push an event to the client every five seconds. The event will be a simple JSON-formatted string with an isChanged property that will be set randomly to true or false. To run this server, use the following command:

node example3-5server.js

The HTML client for this server just has to initiate the EventSource to the correct URL, as shown in Listing 3-6.

Listing 3-6. A Server-sent Event Client

<!DOCTYPE HTML>

<html>

<head>

<title>The HTML5 Programmer's Reference</title>

<style>

#changeme { width: 300px;

height: 300px;

border: 1px solid black;

overflow: auto;

}

</style>

</head>

<body>

<h1>Server-sent Events Demonstration</h1>

<div id="changeme"></div>

<script>

// The URL for our event stream. Note that we are not specifying a domain or // port, so they will default to the same ones used by the host script.

var strUri = '/example3-5-events';

// Get a reference to the DOM element we want to update.

var changeMe = document.getElementById('changeme');

// Create a new server-side event connection and register an event handler for // the 'message' event.

var serverConnection = new EventSource(strUri);

serverConnection.addEventListener('message', handleSSE, false);

/**

* Handles a server-sent event by parsing the JSON in the data and handling * any changes.

* @param {EventSourceEvent} event The event object from the event source.

*/

function handleSSE(event) { // Parse the JSON string.

var jsonResponse = JSON.parse(event.data);

// Create a new element to append to the DOM.

var newEl = document.createElement('div');

if (jsonResponse.isChanged) {

newEl.innerHTML = 'Change reported.';

} else {

newEl.innerHTML = 'No changes reported.';

}

// Append the new element to the DOM.

changeMe.appendChild(newEl);

}

</script>

</body>

</html>

This client initiates a new EventSource for the event stream’s URL and then attaches a message event handler to it. Every time the server publishes an event, the message event handler is called, the event data is parsed, and the results are appended to the DOM. This client is a lot simpler than your previous polling example because all of the details are handled by the browser now. There’s no need to initiate an XMLHttpRequest object, no need to manage your own timers—all you have to do is initialize an EventSource object and register event handlers.

Server-sent Events only allow for one-way communication from the server to the browser. For full duplex communication, see the section on WebSockets.

WebSockets

SUppOrt LeVeL

Good

In document FACULTAD DE CIENCIAS DE LA COMUNICACIÓN (página 35-43)

Documento similar