-
Notifications
You must be signed in to change notification settings - Fork 0
/
user1.js
47 lines (40 loc) · 1.59 KB
/
user1.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const amqp = require('amqplib');
const readline = require('readline');
async function startUser1() {
const connection = await amqp.connect('amqp://localhost');
const channel = await connection.createChannel();
const exchange = 'direct_exchange';
const queue = 'user1_queue';
await channel.assertExchange(exchange, 'direct', { durable: false });
await channel.assertQueue(queue, { durable: false });
await channel.bindQueue(queue, exchange, 'user2_key');
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
async function sendMessage() {
rl.question('Send message to user2 (or "exit" to quit): ', async (message) => {
if (message.trim().toLowerCase() === 'exit') {
rl.close();
await connection.close();
process.exit(0);
} else {
const timestamp = new Date().toLocaleTimeString();
console.log(`[User2 Recived Message][${timestamp}]: ${message}`);
channel.publish(exchange, 'user1_key', Buffer.from(message));
await sendMessage();
}
});
}
async function receiveMessage() {
channel.consume(queue, (message) => {
readline.cursorTo(process.stdout, 0); // Move cursor to beginning of line
readline.clearLine(process.stdout, 1); // Clear line
const timestamp = new Date().toLocaleTimeString();
console.log(`Msg received from User2 [${timestamp}]: ${message.content.toString()}`);
rl.prompt(true); // Re-print the prompt
}, { noAck: true });
}
await Promise.all([sendMessage(), receiveMessage()]);
}
startUser1().catch(console.error);