I am creating a simple chat app where
- There can be multiple users and multiple chat rooms.
- Each chat room can hold multiple users.
- A rabbitMQ connection is established when the server starts.
- When a user connects to the server, a socket connection is opened in a rabbitMQ channel.
- On sending a message through socket from the client (user), rabbitmq channel pushes it to the exchange using a specific routing key.
- On consuming, if the socket is active then send through it & acknowledge it. If not don't acknowledge it and re queue it.
{
//Creating a new connection
amqp.connect('amqp://localhost', (err, conn) => {
conn.createChannel(function(err, ch) {
ch.assertExchange(exchangeName, 'direct', { durable: false });
const routingKey = // some routing key;
wss.on('connection', (ws, req) => {
// Creating a new queue for the user
ch.assertQueue('', { exclusive: true, persist: true, durable: true }, (err, q) => {
// Binds with the routing key
ch.bindQueue(q.queue, exchangeName, routingKey);
ch.consume(q.queue, (msg) => {
if (ws.readyState === 1) {
ch.ack(msg);
ws.send(` [-] Received ${msg.content.toString()}`);
} else {
// What will come here so that it will be requeued to a new queue with the same routing id?
}
}, { noAck: false });
});
ws.on('message', (message) => {
ch.publish(exchangeName, routingKey, new Buffer(message));
console.log(`[x] Sent ${message} to the exchange with routingKey ${routingKey}`);
});
})
This works correctly when all the users are in socket connected with the server. What I want to implement is when the socket connection dies for an user and if he misses a message based on the routing key (specific to the user), he should be able to receive those messages again whenever he reconnects back with a different queue. I feel this is possible since the messages can be kept in exchange if it is not acknowledged in any queue. But not sure how to implement it.