Manu Manu - 6 days ago 6
Javascript Question

io.emit vs socket.emit

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.

Answer

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

Comments