Socket.io with Rabbitmq for one to one chat

Viewed 887

I'm building a one to one chat with Socket.io and RabbitMQ

My implementation of doing a one to one chat is working, but I'm not sure whether the implementation is correct or not.

  1. roomID is equivalent to for example 42314
  2. the roomID is autogenerated when user matched with another user.
  3. The logic is simple, user A join a room 42314 and it will emit to the server.
  4. Once user A joined the room, he can send a message which emits the message from the client to the server.

    rabbit.connect("amqp://localhost", (connError, connection) => {
       connection.createChannel((channelError, channel) => {
          io.on("connection", (socket) => {
           // This is where user join the room
           // and the channel add a new queue which the room ID
             socket.on("join", (room) => {
               channel.assertQueue(room.roomID, {
                    durable: false,
               });
             socket.join(room.roomID);
           });
    
          // This is the part where user send message to another user
          socket.on("sendMessage", (room) => {
             // Once user send a message, it will send to the queue.
             channel.sendToQueue(room.roomID, Buffer.from(room.message));
    
            // since the queue has the room id, whenever there is a message
           // emit it to the room.
            channel.consume(
               room.roomID,
                (msg) => {
                   console.log(" Received " + msg.content.toString());
    
                   io.in(room.roomID).emit("message", msg.content.toString());
                },
                {
                 noAck: true,
                }
              );
           });
         });
       });
     });
    

My questions are

  1. Does my implementation correct?
  2. Can this architecture work if there is a load balancer?
1 Answers
  1. I think using RabbitMQ adds unnecessary complications and lags. You can achieve this with just socket.io, when you receive message, you immediately emit to recipient

     io.on("connection", (socket) => {
      // This is where user join the room
      // and the channel add a new queue which the room ID
      socket.on("join", (room) => {
        socket.join(room.roomID);
      });
    
      // This is the part where user send message to another user
      socket.on("sendMessage", (room) => {
      // Once user send a message, it will send to the queue.
      // channel.sendToQueue(room.roomID, Buffer.from(room.message));
    
      // since the queue has the room id, whenever there is a message
      // emit it to the room.
      io.in(room.roomID).emit("message", room.message);
      });
     });
    
  2. You will need some sort of sticky session to have implementation work behind a load balancer. You can read more on how to achieve this socket io using multiple nodes

Related