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...