io.emit vs socket.emit

Javascriptnode.jsSocketssocket.io

Javascript Problem Overview


I'm new to socket.io and have run in to something that seems pretty weird. I don't actually know the difference between socket.emit and io.emit but I can't find an explanation anywhere.

io.on('connection', function(socket){
  io.emit('connected')  // <<<< HERE >> socket.emit('connected');
  socket.on('disconnect', function(){
    io.emit('disconnect')
  });
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

server.listen(3000);

That's my server stuff however when I change the io to socket that message only gets displayed when the user who is connecting connects. io.emit sends the message to all users.

Maybe it's supposed to be like that or maybe its just some horrible hack? Let me know if you need the client side HTML.

Javascript Solutions


Solution 1 - Javascript

Here's a supplementary documentation for reference :

socket.emit('message', "this is a test"); //sending to sender-client only

socket.broadcast.emit('message', "this is a test"); //sending to all clients except sender

socket.broadcast.to('game').emit('message', 'nice game'); //sending to all clients in 'game' room(channel) except sender

socket.to('game').emit('message', 'enjoy the game'); //sending to sender client, only if they are in 'game' room(channel)

socket.broadcast.to(socketid).emit('message', 'for your eyes only'); //sending to individual socketid

io.emit('message', "this is a test"); //sending to all clients, include sender

io.in('game').emit('message', 'cool game'); //sending to all clients in 'game' room(channel), include sender

io.of('myNamespace').emit('message', 'gg'); //sending to all clients in namespace 'myNamespace', include sender

socket.emit(); //send to all connected clients

socket.broadcast.emit(); //send to all connected clients except the one that sent the message

socket.on(); //event listener, can be called on client to execute on server

io.sockets.socket(); //for emiting to specific clients

io.sockets.emit(); //send to all connected clients (same as socket.emit)

io.sockets.on() ; //initial connection from a client.

Hope this helps!.

Edit: socket.io docs also contain similar cheatsheet.

Solution 2 - Javascript

The io variable represents the group of sockets. The code you have starts on line one with providing a function in the second parameter that gives you a socket variable every time a new connection is made. The socket variable is only for communicating with each individual connection. You may not see it in the code but there will be one socket variable for each connection established

Solution 3 - Javascript

  • socket.emit will send back message to sender only,
  • io.emit will send message to all the client including sender
  • if you want to send message to all but not back to sender then socket.broadcast.emit

Solution 4 - Javascript

That's a good question. Here is a sample code that might answer your question.

server.js code:

// Listener for incoming Socket connections

io.on('connection', function(socket){
  socket.on('send', function(msg){
    console.log('message received/sending: ' + msg);
    io.sockets.emit('new', msg);
  });
});

index.html code

<body>
    <ul id="messages"></ul>
    <form action="">
        <input id="m" autocomplete="off" />
        <button type="submit">Send</button>
    </form>
    <script src="https://code.jquery.com/jquery-1.11.1.js"></script>
    <script src="https://cdn.socket.io/socket.io-1.4.5.js"></script>
    <script>
        var socket = io();
        function send(msg) {
            console.log("emitting: " + msg);
            socket.emit('send', { "message": msg });
        }

        socket.on('new', function (msg) {
            console.log("msg " + msg.message);
            $('#messages').append($('<li>').text(msg.message));
        });

        $(function () {
            $('form').submit(function (e) {
                e.preventDefault();
                send($('#m').val());
                $('#m').val('');
                return false;
            });
        });
    </script>
</body>

In index.html socket.emit('send', { "message": msg }); this line of code actually sends/emits message to server which is waiting to listen on socket.on('send', function(msg){ this line of code in server.js.

Now io.sockets.emit('new', msg); this line from server.js emits that message to all its sockets and is displayed to users using its listener in index.html that is socket.on('new', function (msg) {.

Simply said Each socket emits its msg to a server(io is an instance of server) and server, in turn, emits it to all connected sockets. That is how msg sent by any user is displayed to all users. I hope it helps!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionManu MassonView Question on Stackoverflow
Solution 1 - JavascriptKent AguilarView Answer on Stackoverflow
Solution 2 - JavascriptkejiView Answer on Stackoverflow
Solution 3 - JavascriptKhim Bahadur GurungView Answer on Stackoverflow
Solution 4 - JavascriptShamaView Answer on Stackoverflow