Boris Zagoruiko
Boris Zagoruiko

Reputation: 13164

Socket.io works with each user seperatly

Giver simple socket.io based web-chat. Node.js code:

io.on('connection', function(socket) {

    // Works well for all users
    socket.emit('send:message', {
        text: 'hello world'
    });

    // Logs text for all users
    console.log('Socket: User connected');

    // Message receive only user that send it
    socket.on('send:message', function (data) {
        socket.emit('send:message', {
            text: data.message
        });
    });

});

After user connection, client code successfully receives hello message (and renders it). But when specific user send message to server, he is the only who receives this message. How can i broadcast each message for each user?

Upvotes: 0

Views: 148

Answers (1)

Piotr Giedziun
Piotr Giedziun

Reputation: 126

You need to use:

socket.broadcast.emit('send:message', {
   text: data.message
});

This way all users (except sender will receive this message). If you want broadcast to everyone (including sender) then you have to use:

io.sockets.emit('send:message', {
       text: data.message
});

You can find more at http://socket.io/docs/#broadcasting-messages

Upvotes: 1

Related Questions