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.
That's a good question. Here is a sample code that might answer your question.
server.js code:
// Listener for incoming Socket connections
index.html code
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 server(io is 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!
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 asocket
variable every time a new connection is made. Thesocket
variable is only for communicating with each individual connection. You may not see it in the code but there will be onesocket
variable for each connection establishedHere's a supplementary documentation for reference.
Hope this helps!.