-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathserver.js
65 lines (53 loc) · 1.87 KB
/
server.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
const express = require("express");
const http = require("http");
const app = express();
const server = http.createServer(app);
const socket = require("socket.io");
const io = socket(server);
require ("dotenv").config();
const path = require("path");
const users = {};
const socketToRoom = {};
io.on('connection', socket => {
socket.on("join room", roomID => {
if (users[roomID]) {
const length = users[roomID].length;
if (length === 4) {
socket.emit("room full");
return;
}
users[roomID].push(socket.id);
} else {
users[roomID] = [socket.id];
}
socketToRoom[socket.id] = roomID;
const usersInThisRoom = users[roomID].filter(id => id !== socket.id);
socket.emit("all users", usersInThisRoom);
});
socket.on("sending signal", payload => {
io.to(payload.userToSignal).emit('user joined', { signal: payload.signal, callerID: payload.callerID });
});
socket.on("returning signal", payload => {
io.to(payload.callerID).emit('receiving returned signal', { signal: payload.signal, id: socket.id });
});
socket.on('disconnect', () => {
const roomID = socketToRoom[socket.id];
let room = users[roomID];
if (room) {
room = room.filter(id => id !== socket.id);
users[roomID] = room;
}
socket.broadcast.emit('user left',socket.id)
});
socket.on('change', (payload) => {
socket.broadcast.emit('change',payload)
});
});
const PORT = process.env.PORT || 8000
if(process.env.PROD){
app.use( express.static(__dirname + '/client/build'));
app.get('*', (request, response) => {
response.sendFile(path.join(__dirname, 'client/build/index.html'));
});
}
server.listen(process.env.PORT || 8000, () => console.log('server is running...'));