-
Notifications
You must be signed in to change notification settings - Fork 2
/
server.js
104 lines (87 loc) · 2.48 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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
const ws = require('ws')
const fs = require('fs')
const https = require('https')
const querystring = require('querystring');
require('dotenv').config()
const privateKeyPath = process.env.PRIVATE_KEY_PATH
const certificatePath = process.env.CERTIFICATE_PATH
let privateKey = fs.readFileSync(privateKeyPath, 'utf8')
let certificate = fs.readFileSync(certificatePath, 'utf8')
const httpsServer = https.createServer({ key: privateKey, cert: certificate })
httpsServer.listen(8091, '0.0.0.0')
httpsServer.on('error', (error) => console.log(error))
const server = new ws.Server({
server: httpsServer
})
const socketsMap = new Map();
class Meeting {
constructor() {
this.instructor = undefined;
this.customer = undefined;
}
sendAll(message) {
if (this.customer) {
this.customer.send(message);
}
if (this.instructor) {
this.instructor.send(message);
}
}
sendMessageToPartner(isInstructorRole, message) {
if (isInstructorRole) {
if (this.customer) {
this.customer.send(message);
}
} else {
if (this.instructor) {
this.instructor.send(message);
}
}
}
setByRole(isInstructorRole, socket) {
if (isInstructorRole) {
if (this.instructor) {
this.instructor.close()
}
return this.instructor = socket
} else {
if (this.customer) {
this.customer.close()
}
return this.customer = socket
}
}
bothInMeeting() {
if (this.instructor && this.customer) {
return true
} else {
return false
}
}
}
server.on('connection', function (socket, req) {
const queryParams = querystring.parse(req.url.replace(/(^\/)|(\?)/g, ''))
const meetingId = queryParams.meetingId
const isInstructorRole = queryParams.isInstructorRole === 'true'
if (!meetingId) {
return;
}
if (!socketsMap.has(meetingId)) {
socketsMap.set(meetingId, new Meeting())
}
const meeting = socketsMap.get(meetingId)
meeting.setByRole(isInstructorRole, socket)
console.log('new connection', isInstructorRole ? 'instructor':'customer', meetingId)
socket.on('message', onMessage)
socket.on('close', function () {
meeting.setByRole(isInstructorRole, undefined)
})
function onMessage (message) {
console.log('on message from', isInstructorRole ? 'instructor':'customer')
meeting.sendMessageToPartner(isInstructorRole, message)
}
if (meeting.bothInMeeting()) {
console.log('both partners are here')
meeting.sendAll('ready')
}
})