Socket.io - Broadcasting SOCKET.IO

Socket.io - Broadcasting  

Socket.io - Broadcasting

Broadcasting in Socket.io

The next goal is for us to emit the event from the server to the rest of the users.

In order to send an event to everyone, Socket.IO gives us the io.emit:

io.emit('some event', { someProperty: 'some value', otherProperty: 'other value' }); // This will emit the event to all connected sockets

If you want to send a message to everyone except for a certain emitting socket, we have the broadcast flag for emitting from that socket:

io.on('connection', function(socket){
  socket.broadcast.emit('hi');
});

In this case, for the sake of simplicity we’ll send the message to everyone, including the sender.

io.on('connection', function(socket){
  socket.on('chat message', function(msg){
    io.emit('chat message', msg);
  });
});

And on the client side when we capture a chat message event we’ll include it in the page. The total client-side JavaScript code now amounts to:

<script>
  $(function () {
    var socket = io();
    $('form').submit(function(e){
      e.preventDefault(); // prevents page reloading
      socket.emit('chat message', $('#m').val());
      $('#m').val('');
      return false;
    });
    socket.on('chat message', function(msg){
      $('#messages').append($('<li>').text(msg));
    });
  });
</script>

And that completes our chat application, in about 20 lines of code! This is what it looks like:

Download free E-book of SOCKET.IO


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries