Broadcasting messages with socket.io

sockets broadcast preview

Continuing where we left off. We now attempt to send broadcasts to all connected clients.

Lets modify an event to enable broadcasting.

  socket.on('message-from-client', function(msg) {
    console.log(msg);
    socket.broadcast.emit('broadcast-to-client',{ message: msg.message });
  });

We add broadcasting in the message-from-client event. When we receive a message from a client we want to send it to other clients. So we execute the broadcast emit function and create a event broadcast-to-client.

socket.broadcast.emit('broadcast-to-client',{ message: msg.message });

You can use the above code where you need to broadcast your message.

In the client we just need to catch this event named broadcast-to-client.

   socket.on('broadcast-to-client', function(data){
        response.innerHTML = data.message;
    });

When we receive a broadcast we update the response jumbotron to view the message we received. We update the current clients’ jumbotron manually. You can see this in the submit button event handler.

    submitBtn.addEventListener("click",function(event){
      var clientMessage = message.value;
      response.innerHTML = clientMessage; 
      socket.emit('message-from-client', {
          message: clientMessage
        });
      event.preventDefault();
    });

We update the current response jumbotron before we emit the message-from-client event and pass the data to the server.

App.js File


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s