In the last section, we set up an event listener on the server listening for that join event, and we did some validation. This at least makes sure we have the name and the room name, both of which are going to be required.
The real next step is to actually use the Socket.io library to join rooms, and this is not going to let us just join rooms but it's also going to give us a different set of methods. We can choose to emit to everybody connected to the server or just to people in specific rooms, and that's exactly what we're going to be doing. We want to emit chat messages just to other people who are also in the room.
Now in order to join, what you do is you call socket.join. The socket.join takes a string name, and we have that name under params.room, just like we used in the previous section:
socket.on('join', (params, callback) => {
if(!isRealString(params.name) || !isRealString(params.room)) {
callback('Name and room name are required.');
}
socket.join(params.room);
callback();
});
We now have a special place for people to talk who are in the same room. Now this is a string so it would be something like The Office Fans, or anything else, and you have to join by the string value. Right now, though, params.room will get the job done.
Now you can also choose to leave a room using socket.leave. The socket.leave, leaving the room by its name, The Office Fans for example, is going to kick you out of that group and you're not going to get those private messages, the messages sent specifically to the group. Now the next step in the process is to figure out how to actually take advantage of this:
socket.on('join', (params, callback) => {
if(isRealString(params.name) || !isRealString(params.room)) {
callback('Name and room name are required.');
}
socket.join(params.room);
// socket.leave('The Office Fans');
callback();
});