-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.mjs
94 lines (75 loc) · 2.27 KB
/
index.mjs
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
import Koa from 'koa'
import Router from 'koa-router'
import path from 'node:path'
import fs from 'node:fs'
import { Server } from 'socket.io'
const __dirname = import.meta.dirname
const PORT = process.env.PORT
const isDev = process.env.IS_DEV === 'true'
const useSSL = process.env.USE_SSL === 'true'
function log(...args) {
if (isDev) {
console.log(...args)
}
}
const app = new Koa()
const router = new Router()
router.get('/', (ctx, _) => {
const filePath = path.join(__dirname, 'index.html')
let html = fs.readFileSync(filePath, 'utf8')
html = html.replace('{{ ICE_SERVERS }}', JSON.parse(JSON.stringify(process.env.ICE_SERVERS)))
ctx.type = 'text/html'
ctx.body = html
return
})
app.use(router.routes())
// app.use(serve(path.resolve(__dirname, 'dist')))
let httpServer
if (useSSL) {
const https = await import('node:https')
httpServer = https.createServer({
cert: fs.readFileSync(process.env.CERT),
key: fs.readFileSync(process.env.KEY)
}, app.callback())
} else {
const http = await import('node:http')
httpServer = http.createServer(app.callback())
}
const io = new Server(httpServer)
let activeSockets = []
io.on('connection', (socket) => {
const existSocket = activeSockets.find(s => s === socket.id)
if (!existSocket) {
activeSockets.push(socket.id)
io.emit('update user list', {
users: activeSockets
})
}
log(`user [${socket.id}] connected`)
socket.on('disconnect', () => {
log(`user [${socket.id}] disconnected`);
activeSockets = activeSockets.filter(s => s !== socket.id)
io.emit('update user list', {
users: activeSockets
})
});
socket.on('send offer', (data) => {
log(`send offer: ${data.id}, ${socket.id}`)
io.to(data.id).emit('receive offer', { id: socket.id, offer: data.offer })
})
socket.on("send answer", data => {
log(`send answer: ${data.id}, ${socket.id}`)
io.to(data.id).emit("receive answer", { id: socket.id, answer: data.answer });
});
socket.on("send candidate", data => {
log(`send candidate: ${data.id}, ${socket.id}`)
io.to(data.id).emit("receive candidate", { id: socket.id, candidate: data.candidate });
});
socket.on('chat message', (msg) => {
log('message: ' + msg);
socket.broadcast.emit('chat message', msg);
});
})
httpServer.listen(PORT, () => {
console.log(`Server is listening on ${PORT}...`)
})