我正在用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,
}
);
});
});
});
});
我的问题是
我认为使用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);
});
});
你将需要某种粘性会话来在负载均衡器后面进行实施工作。你可以阅读更多关于如何实现这一点 多节点套接字