-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.js
80 lines (57 loc) · 1.82 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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
const express = require('express');
const path = require('path');
const WebSocket = require('ws');
var fs = require('fs');
const app = express();
const imageDir = path.join(__dirname, 'public', 'images');
const imagePaths = fs.readdirSync(imageDir).map(file => path.join(imageDir, file));
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile('views/index.html', {root: __dirname });
});
app.get('/image', (req, res) => {
const randomIndex = Math.floor(Math.random() * imagePaths.length);
res.set('Cache-Control', 'no-cache');
res.set('Content-Type', 'image/jpeg');
res.sendFile(imagePaths[randomIndex]);
});
var server = app.listen(process.env.PORT || 5000, () => {
console.log('Server listening on port 3000');
});
const wss = new WebSocket.Server({server:server})
var waitingRoom = {}
wss.on('connection', ws => {
console.log('Client connected');
ws.on('message', data => {
message = JSON.parse(data.toString())
console.log("ID:"+ws.id+"Message received of type:"+ message.type)
if(message['type']=='joinRoom'){
ws.room = message['room']
ws.sdp = message['sdp']
if(ws.room in waitingRoom){
ws.id=1
ws.friend = waitingRoom[ws.room]
waitingRoom[ws.room].friend = ws
waitingRoom[ws.room].send(JSON.stringify({"type":"roomFull"}))
delete waitingRoom[ws.room]
console.log("ID:1 assigned")
}
else{
waitingRoom[ws.room] = ws
ws.id = 0
console.log("ID:0 assigned")
}
ws.send(JSON.stringify({type:"joined"}))
}
else{
if("friend" in ws){
ws.friend.send(data.toString())
console.log("Sending answer")
}
}
});
ws.on('close', function close() {
console.log('Client disconnected');
delete waitingRoom[ws.room]
});
});