More on events

In the previous section, we saw how we can use custom events over a socket. The interesting thing is that just like your messages, events can also be broadcast. Let us see how we can use an event broadcast to announce the entry of a participant in our chat room.

For this, the first thing we will do is start emitting a new user_entered event from the server, with the name of the user in the data once the user has joined the chat. Let us change our routes/socket.js file to do this. We will add our code to broadcast the user_entered event once the username is set.

    socket.on("set_name", function(data){
      socket.set('nickname', data.name, function(){
         socket.emit('name_set', data);
     socket.send(JSON.stringify({type:'serverMessage', 
                  message: 'Welcome to the most interesting" +  
                                              "chat room on earth!'}));
     socket.broadcast.emit('user_entered', data);
      });
    });

To send a broadcast to all the clients connected on this socket, we use the emit method, but on socket.broadcast rather than on socket itself. The signature of the method is the same.

Now, the user_entered event will be sent to all the connected clients, so we will need to add an event handler in the client chat.js file.

socket.on('name_set', function(data){

  // EXISTING CODE

  socket.on("user_entered", function(user){
    $('#messages').append('<div class="systemMessage">' + 
                       user.name + ' has joined the room.' + '</div>'),
  });
});

Here, we are adding an event handler for the user_entered event and then displaying the message to the user. Let us start our server once again and log in to our chat room:

More on events

The first user's chat room

Now open another browser window and log in with a different name:

More on events

The second user's chat room

As you will notice, in the first user's window, we will see the entrance message for both Friend001 and Friend002, and for Friend002 in the second user's (Friend001) window.

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

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