Book Image

Node.js Blueprints

By : Krasimir Stefanov Tsonev
Book Image

Node.js Blueprints

By: Krasimir Stefanov Tsonev

Overview of this book

Table of Contents (19 chapters)
Node.js Blueprints
Credits
About the Author
About the Reviewers
www.PacktPub.com
Preface
Index

Adding Socket.IO


The implementation of the chat requires the code to be written in both places: at the server side and the client side. We will continue with the Node.js part by extending the previous code, as follows:

var io = require('socket.io').listen(app);
io.sockets.on('connection', function (socket) {
  socket.emit('welcome', { message: 'Welcome!' });
  socket.on('send', function (data) {
      io.sockets.emit('receive', data);
  });
});

The http.createServer method returns a new web server object. We have to pass this object to Socket.IO. Once everything is done, we have access to the wonderful and simple API. We may listen for incoming events and send messages to the users who are attached to the server. The io.sockets property refers to all the sockets created in the system, while the socket object, passed as an argument to the connection handler, represents only one individual user.

For example, in the preceding code, we are listening for the connection event, that is, for a new...