-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
71 lines (54 loc) · 1.65 KB
/
index.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
const express = require('express');
const app = express();
app.enable('trust proxy');
const path = require('path');
const { v4: uuidv4 } = require('uuid');
const server = require('http').Server(app);
const cors = require('cors');
const io = require("socket.io")(server
);
const { ExpressPeerServer } = require('peer');
const peerServer = ExpressPeerServer(server, {
debug: true,
});
const roomToSockets = {};
// Middlewares
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname, 'views'));
app.use(express.static(path.join(__dirname, 'public')));
app.use('/peerjs', peerServer);
app.use(cors());
app.get('/', (req, res) => {
res.redirect(`/${uuidv4()}`);
});
app.get('/:roomID', (req, res) => {
res.render('room', { roomId: req.params.roomID });
});
io.on('connection', socket => {
socket.on('join-room', (roomId, userId) => {
socket.join(roomId)
socket.to(roomId).emit('user-connected', userId);
// Add the socket to the room's connections
if (!roomToSockets[roomId]) {
roomToSockets[roomId] = [socket];
} else {
roomToSockets[roomId].push(socket);
}
// messages
socket.on('message', (message) => {
//send message to the same room
io.to(roomId).emit('createMessage', message)
});
socket.on('disconnect', () => {
socket.to(roomId).emit('user-disconnected', userId);
// Remove the socket from the room's connections
if (roomToSockets[roomId]) {
roomToSockets[roomId] = roomToSockets[roomId].filter(s => s !== socket);
}
})
})
})
const PORT = process.env.PORT || 3000;
server.listen(PORT, () => {
console.log(`Server listening on port ${PORT}`);
});