DEV Community

Ali Hamza
Ali Hamza

Posted on

Day 168 of Learning MERN Stack

Hello Dev Community! ๐Ÿ‘‹

It is officially Day 168 of my full-stack web development journey! Today, I established the real-time websocket foundation and cloud storage helper utilities for QuickChat using Socket.io, Express, and Cloudinary! โšกโš™๏ธ


๐Ÿ› ๏ธ Technical Breakdown: Sockets & Cloud Infrastructure

As captured in my implementation snapshots (Screenshots 411 & 412):

1. Real-time Socket Server Module (socket.js)

  • Configured Socket.io server instance with CORS origin wildcarding.
  • Maintained an in-memory userSocketMap object linking authenticated userId instances to active socket session identifiers (socket.id).
  • Implemented live online user broadcasting (getOnlineUser) across client connections:

javascript
  io.on('connection', (socket) => {
    const userId = socket.handshake.query.userId;
    if (userId) userSocketMap[userId] = socket.id;

    io.emit('getOnlineUser', Object.keys(userSocketMap));

    socket.on('disconnect', () => {
      delete userSocketMap[userId];
      io.emit('getOnlineUser', Object.keys(userSocketMap));
    });
  });
Enter fullscreen mode Exit fullscreen mode

Top comments (0)