0
This script should be a command-line chat type only for rabbitmq study.
Executions of the program would be opened in parallel. Each execution creates a Sumer from the same queue and all text sent by a program execution should be sent to all consummers via an exchange of type fanout.
It turns out that although I set up exchange as fanout it is not broadcasting the messages. It is behaving like a load Sound sending the message to each Sumer at a time.
const amqplib = require('amqplib');
const readline = require("readline");
class Chat {
async init() {
await this.configureChannel();
await this.configureConsumer();
await this.configureCommandLine();
}
async configureChannel() {
const conn = await amqplib.connect('amqp://guest:guest@localhost:5672');
const ch = await conn.createChannel();
await ch.assertExchange("chat", "fanout", {});
const { queue } = ch.assertQueue('messages');
await ch.bindQueue(queue, 'chat', '');
this.ch = ch;
}
async configureConsumer() {
await this.ch.consume("messages", logMessage);
function logMessage(msg) {
if (msg.content)
console.log("\n[*] Recieved message: '%s'", msg.content.toString())
}
}
async configureCommandLine() {
const commandLine = readline.createInterface({
input: process.stdin,
output: process.stdout
});
this.commandLine = commandLine;
}
async run() {
const prompt = () => {
this.commandLine.question("Message: ", async (mensagem) => {
debugger;
if (mensagem === "sair") {
return this.commandLine.close();
}
await this.ch.publish("chat", 'messages', Buffer.from(mensagem), {});
prompt();
});
}
await this.init();
console.log("\nChat\n");
prompt();
}
}
const chat = new Chat();
chat.run();