DEV Community

tnguyen303
tnguyen303

Posted on • Edited on

Journey to a Full Stack Developer - ep. 3 - Setup Socket.io part 2

This week, we're going to pick up from last week post about how to integrate Socket.io package in your Node application. Socket.io is a package that allows pushing data to specific or all users who are interacting with the application, in real time, such as a chat application, a Facebook UI where you see real-time notifications.

Continuing from my last episode, we currently have the server file completely set up:

const express = require("express");
const app = express();
//http package lets you run server without Express, socket.io requires more control that is provided with this package
const server = require("http").createServer(app);
const io = require("socket.io")(server);

require("./sockets/message-sockets")(io);

This is our front-end javascript code that gets run by the html file, it contains a function that sends a chat message to our database via a POST route (the ajax call) AND additionally send that same message to our socket "listener" file that handles real-time data:

const sendMessage = function(event) {
  const message = $("#message").val();
  event.preventDefault();
    //prepare our data to be sent across your application
    const newMessage = {
      message: message,
      sender: sender,
      recipient: recipient
    };
    //send to server, calling new-message to reference in message-sockets.js
    $.ajax({
      url: `/api/chat/${sender}/${recipient}`,
      method: "POST",
      data: newMessage
    });
    //this is the magic sauce, socket.emit sends data to our server which then gets redirected by the message-sockets.js file to other people's browser. The tag is "new-message" and this must match the receiving socket.on in your message-sockets.js file.
    socket.emit("new-message", newMessage);
};

As you can tell, we are calling a "message-sockets" file to be used by the Socket.io package. This is a JavaScript file that will hold the server-side "handling" of the real-time data:

//this is message-sockets.js file in sockets subfolder
module.exports = function(io) {
  console.log("running");
  //this .on listener runs every time a user connects
  io.on("connection", function(socket) {
    //SOCKET ROUTES:

    // push to all sockets, can be used to notify users of a New Version Update is available
    socket.on("new-message-to-all", function(data) {
      io.emit('emit-message-to-all',data);
    });

    //push to specific (private) sockets, can be used to send private info such as messages to a user or group
    socket.on("new-message", function(data){
      const socket1 = users[data.sender];
      const socket2 = users[data.recipient];
      socket1.emit('emit-message', data);
      socket2.emit('emit-message', data);
    });

  });
};

After the server has redirected our new-message data, the front-end code must have a function to listen for this new data, now called "emit-message" and render it to the targeted users:

//this is my client-side javascript file that runs when my html runs
//display message on private sockets
socket.on("emit-message", function(data) {
  //this is a simple function to render a new message to the website
  renderMessageList(data);
});

It looks complicated and long but the whole code can be summarized as, In socket.io, we have three steps to send real-time data:

  1. Emit - this is just a notice that tells the server there is new data, along with the new data and a tag
  2. On (server-side) - this is basically an event listener that listens for the specific "Emit" tag, then performs an Emit back to the client-side to targeted "sockets" or users.
  3. On (client-side) - this, again, is just a listener for the redirected data, in step 2, and perform a function, usually a simple function that display this data to the client's browser.

Next week I'm going to share what I have learned in testing with you. Hopefully this has been an informative how-to and I will be glad to know I had helped someone in need!

Top comments (0)