I have two separate files that one is server-side JS.
The other one is dynamically generated client-side PHP.
Those two files are successfully able to communicate each other through Socket.IO.
I understand that I can restrict namespace by using .of() but that cannot be used
to handle dynamically created chat rooms.
So I have decided to use both
.of('/chat')
and the room feature
.join('room name')
I could find server-side example and could not find client-side example with it.
Below is the only given server-side code snippet from Socket.IO github
var io = require('socket.io').listen(80);
io.sockets.on('connection', function (socket) {
socket.join('justin bieber fans');
socket.broadcast.to('justin bieber fans').emit('new fan');
io.sockets.in('rammstein fans').emit('new non-fan');
});
1) I’m having trouble understanding below part.
socket.broadcast.to('justin bieber fans').emit('new fan');
io.sockets.in('rammstein fans').emit('new non-fan');
What is difference between those two?
2) why not using
socket.to('room name').emit('event')
instead of
io.sockets.in('room name').emit('new non-fan');
3) Lastly, I have found some documentation that using
.send()
instead of
.emit()
Somewhat .send() does not work for me and I want to know difference between those two.
Thanks and I apologize for multiple questions about Socket.IO.
I have not used Socket.IO in quite some time, but
1.) As the documentation states: “Broadcasting means sending a message to everyone else except for the socket that starts it.”
After some searching with the Socket.IO code, you can take a look at Socket.prototye.packet, in /lib/socket.js.
When you do your first call, you are setting the user to the “justin bieber fans” room, and broadcasting “new fan” for everyone but the socket.
In the second instance, you are broadcasting for everyone in ‘rammstein fans’ to send ‘new non-fan’.
2.)
In the first call, you are emitting ‘event’ just for the single user, and the message to that single room.
In the second call, you are sending for everyone in that room.
3.)
Once again, looking at the source code, they both look pretty similar, except that socket.io protocol accepts 3 different kind of messages: “event”, “json”, “message”.
With .send, you can send a json string, or a message.
With .emit, you are going to send an event to the client.
It does not make much a difference, they are almost handled the same internally, but you should use the one that best fits your needs.