GAZAR

Principal Engineer | Mentor

Building a Real-Time Chat Application with Socket.IO and Express.js

Building a Real-Time Chat Application with Socket.IO and Express.js

In today's interconnected world, real-time communication is paramount. Whether it's for customer support, team collaboration, or social interaction, having a reliable chat application is essential. In this tutorial, we'll walk through building a simple chat application using Socket.IO and Express.js, where messages are stored in memory. We'll utilize events like "chat:receive" and "chat:broadcast" for seamless communication between clients.

So on the service side:

const io = new Server(server, {
  path: "/chat",
  cors: {
    origin: "*",
    methods: ["GET", "POST"],
  },
});

io.on("connection", (socket) => {
  socket.emit("chat:receive", chatQueue.getQueue());
  socket.on("chat:send", (data) => receive(io, socket, chatQueue, data));
});

// And receive is
const receive = async (io, socket, chatQueue, data) => {
  chatQueue.enqueue(data);
  if (chatQueue.size() > 12) {
    chatQueue.dequeue();
  }
  io.sockets.emit("chat:receive", chatQueue.getQueue());
};

Then on the client side:

const handleReceive = (data: ChatMessage[]) => {
    setChatHistory(data);
};

useEffect(() => {
    if (socketIoIsLoaded) {
      window.socket = window.io("http://localhost:3000/", {
        transports: ["websocket"],
        path: "/chat",
      });

      window.socket.on("chat:receive", handleReceive);

      window.socket.on("connect_error", () => {
        console.log("connect_error");
      });
    }
}, [socketIoIsLoaded]);

In this tutorial, we've built a simple real-time chat application using Socket.IO and Express.js. We utilized events like "chat:receive" and "chat:broadcast" for seamless communication between clients. While this example stores messages in memory, you can extend it further by integrating with a database for persistent storage or adding more features like user authentication and private messaging. Happy coding!