-
Notifications
You must be signed in to change notification settings - Fork 10
/
server.js
103 lines (82 loc) · 1.92 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
const fs = require('fs')
const express = require('express')
const cors = require('cors')
const bodyParser = require('body-parser')
const app = express()
app.use(cors())
/**
* Store all connections in place
*/
const connections = []
/**
* This middleware sets up Server-Sent Events.
*/
const sse = (req, res, next) => {
const connection = {
uuid: req.params.uuid,
res: res
}
// SSE protocol works by setting the `content-type` to `event-stream`
res.writeHead(200, {
'Content-Type': 'text/event-stream',
'Cache-Control': 'no-cache',
'Connection': 'keep-alive'
})
// Enrich the response object with the ability to send packets
res.sseSend = (data) => {
try {
res.write('data: ' + JSON.stringify(data) + '\n\n')
} catch (e) {
connections.pop(connection)
clearInterval(res.interval)
}
}
// Setup an interval to keep the connection alive
res.interval = setInterval(() => {
res.sseSend({
type: 'ping'
})
}, 5000)
// Store the connection
connections.push(connection)
next()
}
app.use(bodyParser.json())
app.post('/announce', (req, res) => {
const uuid = req.body.uuid
const packet = {
type: 'announce',
uuid: uuid
}
connections.forEach((c) => {
// Don't announce to self
if (c.uuid !== uuid) {
c.res.sseSend(packet)
}
})
res.sendStatus(200)
})
app.post('/:uuid/signal', (req, res) => {
const uuid = req.params.uuid
const packet = {
type: 'signal',
initiator: req.body.initiator,
data: req.body.data,
uuid: req.body.uuid
}
var result = false
connections.forEach((c) => {
if (c.uuid === uuid) {
c.res.sseSend(packet)
result = true
}
})
res.sendStatus(result ? 200 : 404)
})
app.get('/:uuid/listen', sse, (req, res) => {
res.sseSend({
type: 'accept'
})
})
const port = process.env.PORT || 3000
app.listen(port, () => console.log(`Listening on port ${port}...`))