As a preface
Our client wanted to make a chat with blackjack and courtesans on the project. NodeJs is not my profile and I didn’t have much experience with it. (Therefore, the article is addressed to the same novices in node and socket.io, just like myself).
Nevertheless, I did one project and it was connected - yes, yes with
socket.io . So this time I thought that it would be perfect. Moreover, the site even has a demo and sample
chat . But, as always in life, everything turns out to be more complicated than in the examples.
Chat from the example sent messages to absolutely everyone. It was clear that somehow you need to add users to the room. And if we take a look at the documentation for
socket.io rooms and namespaces , it describes how to work with rooms, but it’s unclear how they work. Here I propose to deal with this.
And to understand how rooms work. Let's start from the very beginning - let's see what the io object is.
')
var io = require('socket.io')(http);
As you can see, IO stores all the identifiers of the connected sockets. And that means, knowing the socket identifier, we can find it.
var socket = io.sockets.connected[socketId];
Those. each socket at creation receives a unique identifier by which it can be found. And now let's take a look at the socket connected to a particular room.
var room = uuid.v4(); socket.join(room);
As you can see, the default socket ID is automatically added to rooms. In the same place we can find and ID of our room. Thus, when we send a message to the room
io.sockets.to(room).emit('message', {message: "details"});
I can assume that IO goes through the rooms of the terminated sockets and sends a message to them.
It's simple enough, right? But I must admit at the beginning I could not cope with the understanding of how the rooms work. So I hope this article will be useful to someone.