HTML and CSS Reference
In-Depth Information
Listing 11-6. The onopen Function
ws.onopen = function() {
messageContainer.innerHTML += "Preparing to send message";
var message = {date: new Date()};
ws.send(JSON.stringify(message));
messageContainer.innerHTML += "Sent message."
};
Upon receipt of a message, you parse the JSON and print out each key and its value, as shown in Listing 11-7.
Listing 11-7. Parsing and Printing JSON Key Values
ws.onmessage = function (evt) {
var received_msg = evt.data;
var json = JSON.parse(received_msg);
messageContainer.innerHTML = "Message received: \n";
for (var key in json) {
messageContainer.innerHTML += "key: "+json[key]+"\n";
}
};
Using Socket.IO
Socket.IO is a cross-platform library for Node.js that provides a Websocket-like API for real-time communication
in web applications. The library is a mature and de facto standard in the JavaScript community for implementing
solutions, using WebSockets. Socket.IO is described as a WebSocket-like API for two reasons:
1. Socket.IO is a superset of WebSockets.
2.
WebSockets are one of many transport methods an application can use for
communication.
In addition to WebSockets, readily available in modern browsers, Socket.IO has fallback transport methods for
older browsers and mobile operating systems:
1.
Adobe Flash Sockets
2.
AJAX long polling
3.
AJAX multipart streaming
4.
Forever Iframe
5.
JSON with padding (JSONP) polling
The availability of all these techniques means that even Internet Explorer 5.5, which was released in 1999, can use
Socket.IO . It is (hopefully) unlikely that users will have a browser that old, but Socket.IO allows you to learn a single
API, target the best of the breed, and let things degrade naturally.
Getting Started
Provided that you already have a Node.js install on your machine (for more information, see http://nodejs.org ) ,
you can install Socket.IO with node-packaged modules (npm), using the following command:
npm install socket.io
 
Search WWH ::




Custom Search