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!