HTML and CSS Reference
In-Depth Information
io.sockets.on('connection', function (socket) {
socket.on('message', function (data) {
After being bound to an application (app) instance to listen for new connections, the io object attaches a
function to any inbound socket to echo back received input. You may have noticed that the form
socket.on ('<name of event>', function(args) { })
is present in both your front-end and back-end code. It also doesn't require a confusing ws:// or wss:// protocol.
Fewer APIs to learn makes for happier developers.
You can run the Node.js example by executing this code:
npm install
node app
Using Events
In the previous section, I briefly covered events, mostly adhering to the general WebSocket API. In this section, you
will work with events further in the completion of a full-fledged application. In this example, we want something that
is both easy to code and not obscured by a bunch of Canvas or Web Graphics Library (WebGL) code, so you will use a
simple quiz game, with an associated chat box.
When the user navigates to the app, you establish a socket connection and register events for your app to handle.
Three custom events, question , answer , and chat , receive questions, send and receive answers, and send and receive
chat messages, respectively. The code resides in the app.js file, in the examples/ directory. Each
event has its own handler function, as shown in Listings 11-10 and 11-11.
Listing 11-10. The Custom Events' Handler Functions
App.prototype.setupClient = function() {
this.socket = io.connect();
this.socket.on('message', this.handleMessage);
this.socket.on('question', this.displayQuestion);
this.socket.on('answer', this.displayAnswer);
this.socket.on('chat', this.displayChatMessage);
this.time = new Date().getTime();
The code for sending a chat message is shown in Listing 11-11.
Listing 11-11. Sending a chat Message
App.prototype.sendChatMessage = function() {
var text = $('#message').get(0).value;
if (text == "") return;
app.socket.emit('chat', {message: text});
app.displayChatMessage({message: text});
Search WWH ::

Custom Search