我正在与Socket.io和RabbitMQ建立一对一聊天
我进行一对一聊天的实现正在运行,但是我不确定实现是否正确。
roomID
相当于例如42314
roomID
是自动生成的。42314
,它将发射到服务器。用户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,
}
);
});
});
});
});
我的问题是
答案 0 :(得分:0)
我认为使用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);
});
});
您将需要某种粘性会话,以使实现工作在负载均衡器后面。您可以阅读有关如何实现此socket io using multiple nodes