45 lines
1.2 KiB
JavaScript
45 lines
1.2 KiB
JavaScript
import http from 'http';
|
|
import { Server } from 'socket.io';
|
|
import amqp from 'amqplib/callback_api.js';
|
|
import app from './app.js';
|
|
import { syncDatabase } from './utils/syncDatabase.js';
|
|
|
|
const server = http.createServer(app);
|
|
const io = new Server(server);
|
|
|
|
const RABBITMQ_URL = 'amqp://localhost';
|
|
const QUEUE = 'chat_messages';
|
|
|
|
amqp.connect(RABBITMQ_URL, (err, connection) => {
|
|
if (err) {
|
|
throw err;
|
|
}
|
|
|
|
connection.createChannel((err, channel) => {
|
|
if (err) {
|
|
throw err;
|
|
}
|
|
channel.assertQueue(QUEUE, { durable: false });
|
|
io.on('connection', (socket) => {
|
|
channel.consume(QUEUE, (msg) => {
|
|
const message = JSON.parse(msg.content.toString());
|
|
io.emit('newMessage', message);
|
|
}, { noAck: true });
|
|
socket.on('newMessage', (message) => {
|
|
channel.sendToQueue(QUEUE, Buffer.from(JSON.stringify(message)));
|
|
});
|
|
socket.on('disconnect', () => {
|
|
});
|
|
});
|
|
|
|
syncDatabase().then(() => {
|
|
server.listen(3001, () => {
|
|
console.log('Server is running on port 3001');
|
|
});
|
|
}).catch(err => {
|
|
console.error('Failed to sync database:', err);
|
|
process.exit(1);
|
|
});
|
|
});
|
|
});
|