我正在使用Socket.io和RabbitMQ构建一对一聊天功能。
我的一对一聊天实现已经生效,但我不确定这种实现方式是否正确。
roomID
is equivalent to for example42314
- the
roomID
is autogenerated when user matched with another user. - The logic is simple, user A join a room
42314
and it will emit to the server. 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, } ); }); }); }); });
我的问题是
- 我的实现是否正确?
- 如果有负载均衡器,这个架构能否正常工作?