How rooms in work

    As a preface

    Our client wanted to make a chat with blackjack and courtesans on the project. NodeJs is not my profile and I did not have much experience with it. (Therefore, the article is addressed to the same newcomers to node and, as I myself).

    Nevertheless, I did one project and it was connected - yes, yes with . So this time I thought that it would be perfect. Moreover, the site even has a demo and an example chat . But, as always in life, everything is more complicated than in the examples.

    The 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 rooms and namespaces- it describes how to work with rooms, but it is not clear how they work. Here I propose to deal with this.

    And to understand how the rooms work. Let's start from the very beginning - let's see what the io object is all about.

    var io = require('')(http);


    As you can see, IO stores all the identifiers of connected sockets. And this 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. Now let's take a look at a socket connected to a specific room.

    var room = uuid.v4();


    As you can see, the default socket ID is automatically added to the rooms. There we can find the ID of our room. Thus, when we send a message to the room'message', {message: "details"});

    I can assume that the IO goes through the rooms of the sockets that are connected and sends a message to them.

    It's simple enough, right? But I must confess at the beginning I could not cope with the understanding of how the rooms work. So I hope this article is useful to someone.

    Also popular now: