Socket.io与Rabbitmq进行一对一聊天

时间:2020-05-18 16:14:25

标签: node.js socket.io rabbitmq

我正在与Socket.io和RabbitMQ建立一对一聊天

我进行一对一聊天的实现正在运行,但是我不确定实现是否正确。

  1. roomID相当于例如42314
  2. 与其他用户匹配时,roomID是自动生成的。
  3. 逻辑很简单,用户A加入一个会议室42314,它将发射到服务器。
  4. 用户A进入会议室后,他可以发送一条消息,该消息将消息从客户端发送到服务器。

    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 个答案:

答案 0 :(得分:0)

  1. 我认为使用RabbitMQ会增加不必要的复杂性和滞后性。您可以只用socket.io来实现,当您收到消息时,您立即将其发送给收件人

     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. 您将需要某种粘性会话,以使实现工作在负载均衡器后面。您可以阅读有关如何实现此socket io using multiple nodes

  3. 的更多信息
相关问题