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

问题描述 投票:1回答:1

我正在用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. 如果有负载均衡器的话,这个架构能用吗?
node.js socket.io rabbitmq
1个回答
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. 你将需要某种粘性会话来在负载均衡器后面进行实施工作。你可以阅读更多关于如何实现这一点 多节点套接字

© www.soinside.com 2019 - 2024. All rights reserved.