The client

Now that we have seen how the server works, let's see what the client does. The best part of socket.io is that it provides us the same API on the server and the client. For our chat logic on the client, let's create a file called chat.js in the public/javascripts folder and add the following code to it:

var socket = io.connect('/'), 

socket.on('message', function (data) { 
  data = JSON.parse(data); 
  $('#messages').append('<div class="'+data.type+'">' + data.message + '</div>'), 
}); 

$(function(){ 
  $('#send').click(function(){ 
    var data = { 
      message: $('#message').val(), 
      type:'userMessage' 
    }; 
    socket.send(JSON.stringify(data)); 
    $('#message').val(''), 
  }); 
}); 

The first step in starting the chat is to connect to the server:

var socket = io.connect('/'), 

This will send a connection request to the server from which the page was loaded. This will also negotiate the actual transport protocol and will finally result in the connection event being triggered on the server app.

The following code snippet connects the event handler for the message event:

socket.on('message', function (data) { 
  data = JSON.parse(data); 
  $('#messages').append('<div class="'+data.type+'">' + data.message + '</div>'), 
}); 

All we have to do with the incoming message is to append it to the messages area. We are adding one additional detail here by setting the class property for the newly appended div tag to be of the same type as that of the message. We can later use this to give a different look to the different types of messages.

The last thing to do on the client side is to send the messages from the user. This will be done when the user writes his/her message in the message box and clicks the Send button. So, let's add an event handler to the Send button. The important thing about UI elements' event handlers is that they should be attached once the element is added to the document, that is, after it is created and ready. jQuery provides a convenient method to detect when the document is ready and adds a handler function to execute. There are two ways to do this; one is the following:

$(document).ready(function(){
  //Execute once the document is ready
});

The shortcut for the same is as follows:

$(function(){
  //Execute once the document is ready
});

Once the document is ready, we attach the event handler to the cl ick event of the Send button:

$(function(){ 
  $('#send').click(function(){ 
    var data = { 
      message: $('#message').val(), 
      type:'userMessage' 
    }; 
    socket.send(JSON.stringify(data)); 
    $('#message').val(''), 
  }); 
}); 

On clicking the Send button, we create our data object, setting the content of the message box as message, and type as userMessage. We can then use the socket.send method to send this data to the server. As you can see from the preceding code snippet, the syntax for sending messages from the client is the same as that of the server, and here too the message will be sent as a sting, which we create using JSON.stringify(data).

Like the connection event and other predefined events on the server, we have some predefined events on the client too. These are as follows:

  • socket.on('connect', function () {}): The connect event is emitted when the socket is connected successfully.
  • socket.on('connecting', function () {}):The connecting event is emitted when the socket is attempting to connect with the server.
  • socket.on('disconnect', function () {}): The disconnect event is emitted when the socket is disconnected.
  • socket.on('connect_failed', function () {}): The connect_failed event is emitted when socket.io fails to establish a connection to the server and has no more transports to fall back to.
  • socket.on('error', function () {}): The error event is emitted when an error occurs and it cannot be handled by the other event types.
  • socket.on('message', function (message, callback) {}): The message event is emitted when a message sent by using socket.send is received. The message parameter is the sent message, and callback is an optional acknowledgment function.
  • socket.on('anything', function(data, callback) {}): The anything event can be any event except the reserved events. The data parameter represents the data, and callback can be used to send a reply.
  • socket.on('reconnect_failed', function () {}): The reconnect_failed event is emitted when socket.io fails to reestablish a working connection after the connection was dropped.
  • socket.on('reconnect', function () {}): The reconnect event is emitted when socket.io is successfully reconnected to the server.
  • socket.on('reconnecting', function () {}): The reconnecting event is emitted when the socket is attempting to reconnect with the server.

The last task to be done on the client side is to add socket.io and the chat scripts to our chat room page. Since these will not be used on every page, instead of adding them to layout.jade, we will add these to index.jade.

Remember the change we had made to layout.jade, changing the code from head to block head? It will allow us to append the content from index.jade to the head tag:

block append head 
      script(type='text/javascript', src='/socket.io/socket.io.js') 
      script(type='text/javascript', src='/javascripts/chat.js')

In the following line of code, we are using Jade's functionality to append content to a block in an inherited template from the child element. This is done using the append keyword. The syntax is as follows:

block append <blockname>

The shorter form is as follows:

append <blockname>

The next two lines of code add the script tags by adding socket.io.js and chat.js to our page. You might be wondering where the /socket.io/socket.io.js file comes from, since we neither add it and nor does it exist on the filesystem. This is part of the magic done by io.listen on the server. It creates a handler on the server to serve the socket.io.js script file.

And we are ready. Restart the node server and browse to http://localhost:3000 / to open the chat room. You will see the welcome message, Welcome to the most interesting chat room on earth!, being displayed in the message area.

To see how our chat application works, open it in two separate browser instances. Now you can enter your message in the message box in one of the browsers and click Send. You will see it appear on the message area of both the browsers.

Congratulations! We now have a chat room. If you deploy it to a server or allow access to port 3000 on your system, you can invite your friends to chat.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset