How to restrict customers who receive messages with socket.io

Asked

Viewed 207 times

2

Guys, how do I get this control on the socket.io. I’ll illustrate my situation: imagine I have a list of friends, how do I get my messages to reach only my friends and not all connected clients, like a social network where only those who can see my posts are my friends?

1 answer

3


The ideal in this scenario is to use the concept of Rooms that the socket.io exposes. Basically you group certain sockets, in this case those of your friends, in a "room", so you can send messages/events to this room and everyone in it will receive. A slight complication in this case is that you are someone’s friend and that person is also their friend, so each person has their own room that contains all their respective friends.

A draft of the idea in code:

var io = require('socket.io').listen(80);
var allSockets = {}; // todos os sockets conectados
io.sockets.on('connection', function (socket) {
    allSockets[socket.id] = allSockets;

    // adiciona um amigo na sua sala de amigos e também adiciona você na sala de amigos deste amigo. As salas são representadas pela ID contida no socket da sua conexão ("socket.id")
    socket.on('adicionarAmigo', function(amigoSocketId) {
        socket.join(amigoSocketId); // você ("socket") entra na sala de amigos do seu novo amigo
        allSockets[amigoSocketId].join(socket.id); // seu amigo (o socket em allSockets[amigoSocketId]) entra na sua sala de amigos
    });

    socket.on('enviarParaAmigos', function(message) {
        // aqui você envia a mensagem para todos os sockets que estão na sala "socket.id", que é sala dos seus amigos
        socket.broadcast.to(socket.id).emit('message', message);
    });
});
  • Thank you for the explanation and the draft. I will use it and improve it. Abs

Browser other questions tagged

You are not signed in. Login or sign up in order to post.