-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp_chat.js
93 lines (80 loc) · 2.46 KB
/
app_chat.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
const express = require('express');
const http = require('http');
const { Server } = require('socket.io');
const Stomp = require("stomp-client");
const room = require('./app/chat/controller/chatController');
const login = require('./app/chat/middleware/loginMiddleware');
const {GATEWAY_HOST} = require("./app/commons/config");
Object.assign(global, { WebSocket: require('ws') });
let rooms = {'0': {users:new Set()}};
const app = express();
app.use(express.json());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: 'http://'+GATEWAY_HOST,
methods: ['GET', 'POST']
}
});
const client = new Stomp('activemq', 61613, 'admin', 'password');
client.connect(function(sessionId) {
console.log('Connected to ActiveMQ with session ID:', sessionId);
});
/**
* @param {{ roomId: string, content: string, user: string, timestamp: string }} msg
*/
function sendMessage(msg){
if (''+msg.roomId === '0'){
console.log("Sending to all")
io.emit('receiveMessage', msg);
} else {
console.log("Sending to room "+msg.roomId)
io.to(msg.roomId).emit('receiveMessage', msg);
}
const message = JSON.stringify(msg);
try {
client.publish(`/queue/game`, message, function (_err) {
console.error("Could not send " + message)
});
}catch (e){
console.error("ActiveMQ Err")
console.error(e);
}
}
room.registerRoomHttpApi(app, rooms, {send: sendMessage})
login.registerTokenHttpApi(app);
login.registerTokenMiddleware(io);
io.on('connection', (socket) => {
console.log('A user connected:', socket.login);
rooms['0'].users.add(socket.login);
socket.on('joinRoom', (roomId) => {
console.log(`User ${socket.id} joined room ${roomId}`);
if (''+roomId === '0') return;
if (rooms[roomId]) {
socket.join(roomId);
console.log(`User ${socket.id} joined room ${roomId}`);
} else {
socket.emit('error', 'Room does not exist');
}
});
socket.on('sendMessage', (message) => {
const { roomId, content } = message;
if (''+roomId !== '0' && !rooms[roomId]) {
socket.emit('error', 'Room does not exist');
}
const toSendMsg = {
roomId,
content,
user: socket.login,
timestamp: new Date().getTime()
}
sendMessage(toSendMsg);
});
socket.on('disconnect', () => {
console.log('A user disconnected:', socket.id);
rooms['0'].users.delete(socket.login);
});
});
server.listen(8089, () => {
console.log('Server listening on port 8089');
});