使用RabbitMQ的Socket.io实现一对一聊天

3
我正在使用Socket.io和RabbitMQ构建一对一聊天功能。 我的一对一聊天实现已经生效,但我不确定这种实现方式是否正确。
  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,
                }
              );
           });
         });
       });
     });
    

我的问题是

  1. 我的实现是否正确?
  2. 如果有负载均衡器,这个架构能否正常工作?
1个回答

1
  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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接