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

var express = require('express');
var path = require('path');
var app = express();
var server = require('http').Server(app);
var io = require('socket.io')(server);
var port = 8080;
app.use(express.static(path.join(__dirname, "public")));
io.on('connection', function(socket) {
console.log('new connection made'); // send to the output
socket.emit('message-from-server', {
greeting: 'Hello from Server'
});
socket.on('message-from-client', function(msg) {
console.log(msg);
socket.broadcast.emit('broadcast-to-client',{ message: msg.message });
});
});
server.listen(port, function() {
console.log("Listening on port " + port);
});


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