Socket.io only sends data to the client that makes the request

I am sending data to all clients, but I only need to send data to one client ( who are making the request ).

app.post(.....){
  myModel.save(function (err) {
    if (err) return handleError(err);

    ///send to all
    io.sockets.emit("ev", { ...... });

    //// send to one client
    ...... 

 });
}

      

There is a function named io.sockets.emit

but not io.socket.emit

.

+3


source to share


1 answer


I am assuming that in the post method you have identified the user or session.

This way, you can create a room for each user to emit afterwards.

client.js

var room = "#usernameRoom";

socket.on('connect', function() {
   socket.emit('privateroom', room);
});

socket.on('privatemessage', function(data) {
   console.log('Incoming private message:', data);
});

      



server.js

io.sockets.on('connection', function(socket) {
    var socket_room;

    socket.on('privateroom', function(room) {
        socket_room = room;
        socket.join(room);
    });

    socket.on('disconnect', function() {
        if (socket_room) {
            socket.leave(socket_room);
        }
    });
});


app.post(.....){
  myModel.save(function (err) {
    if (err) return handleError(err);

    ///send to all
    io.sockets.emit("ev", { ...... });

    //// send to one client

    // now, it easy to send a message to just the clients in a given private room
    privateRoom = "#usernameRoom";
    io.sockets.in(privateRoom ).emit('privatemessage', 'Never reveal your identity!');

 });
}

      

hope it helps

+3


source







All Articles