Restricting clients receiving messages with socket.io

2

Well, how do I get this control on socket.io. I'll illustrate my situation: imagine that I have a list of friends, how do I get my messages to only my friends and not all connected clients, like a social network where only those who can see my publications are my friends? / p>     

asked by anonymous 15.01.2016 / 19:48

1 answer

2

The ideal in this scenario is to use the rooms concept that 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. One slight complication in this case is that you are friends with someone and this person is also your friend, so each person has their own room that contain all their respective friends.

A rough 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);
    });
});
    
17.01.2016 / 19:00