SOCKET FOR OUR LIVE INTERACTION

 HERE, WE USE SOCKET.IO FOR OUR LIVE INTERACTION (CHATS) .

WE CREATE THREE PROPERTIES NAMELY, MESSAGES, CONNECTIONS,TIMEONLINE.

THESE THREE ARE USED TO STORE DATA. MESSAGES TO STORE THE MESSAGES SENT BY THE USERS, CONNECTIONS TO STORE THE NUMBER OF CONNECTIONS (SOCKETS) AND TIME ONLINE DENOTES THE TIME SPENT ONLINE BY THE USER.

AS WE KNOW FROM THE PREVIOUS POST, IN SOCKET. IO WE USE TWO OF THE IMPORTANT FUNCTIONS SOCKET.ON ( TO RECEIVE) AND SOCKET.EMIT ( TO EMIT).

WE CREATE A NEW FILE, IN CONTROLLERS FOLDER CALLED SOCKETCONTROLLER.

IN SOCKETCONTROLLER.JS

const { Server } = require("socket.io");
let messages = {};
let connections = {};
let timeOnline = {};
module.exports.SocketConnection = (server) => {
  const io = new Server(server, {
    cors: {
      origin: "*", // TO SOLVE CORS ERROR
      methods: ["GET", "POST"],
      credentials: true,
    },
  });

  io.on("connection", (socket) => {
    socket.on("joined-chat", (path) => {
      if (connections[path] === undefined) { //IF IN CASE THERE ARE NO CONNECTIONS
        connections[path] = [];
      }
      connections[path].push(socket.id); // IF A CONNECTION EXIST, WE PUSH THE
SOCKET ID INTO IT.
      timeOnline[socket.id] = new Date();

      for (let i = 0; i < connections[path].length; i++) {
        io.to(
          connections[path][i].emit("user-joined"),
          socket.id,
          connections[path]
        );
      }
      if (messages[path] !== undefined) {
        for (let i = 0; i < messages[path].length; i++) {
          io.to(socket.id).emit(
            "chat-message",
            messages[path][i]["data"],
            messages[path][i]["sender"],
            messages[path][i]["socketID-sender"]
          );
        }
      }
    });
    socket.on("signal", (toId, message) => {
      io.to(toId).emit("signal", socket.id, message);
    });
    socket.on("chat-msg", (data, sender) => {
      const [matchingRoom, found] = Object.entries(connections).reduce(
        ([room, isFound], [roomKey, roomVal]) => {
          if (!isFound && roomVal.includes(socket.id)) {
            return [roomKey, true];
          }
        },
        ["", false]
      );

      if (found) {
        if (messages[matchingRoom] === undefined) {
          messages[matchingRoom] = [];
        }
        messages[matchingRoom].push({
          sender: sender,
          data: data,
          "socketID-sender": socket.id,
        });
        connections[matchingRoom].forEach((element) => {
          io.to(element).emit("chat-msg", data, sender, socket.id);
        });
      }
    });
    socket.on("disconnect", () => {
      let diffTime = Math.abs(timeOnline[socket.id] - new Date());

      const [matchingRoom, found] = Object.entries(connections).reduce(
        ([Key, Val]) => {
          for (let i = 0; i < Val.length; i++) {
            io.to(connections[Key][i].emit("user-left", socket.id));
          }
          const index = connections[Key].indexOf(socket.id);
          connections[Key].splice(index, 1);

          if (connections[Key].length == 0) {
            delete connections[Key];
          }
        }
      );
    });
  });
};

WE WILL BE DISCUSSING MORE ABOUT THIS , WHILE WE ARE WORKING ON THE FRONTEND






Comments

Popular posts from this blog

MIDDLEWARE.JS

MODELS

AUTHENTICATION PAGE