-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
101 lines (84 loc) · 2.2 KB
/
Copy pathserver.js
File metadata and controls
101 lines (84 loc) · 2.2 KB
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
const {BehaviorSubject} = require('rxjs');
const express = require('express');
const cors = require('cors');
const app = express();
app.use(cors());
app.use(express.urlencoded({
extended: true
}));
app.use(express.json());
app.use(express.static('public'))
const port = 3000;
let data = {
bar: 0,
defaults: {
containers: ['ITD01', 'ITD02', 'ITD03', 'ITD04', 'ITD05'],
time: 20,
},
step: 1,
username: '',
game: {
step: 1,
score: 0,
},
containers: {
stock: [],
loaded: [],
selected: '',
},
time: {
remaining: 0,
running: false,
display: '00:00',
started: null
}
};
const lastEntry = new BehaviorSubject(data);
let subscriptions = {
};
app.use(express.static('public'));
app.get('/', (req, res) => res.send('Hello World!'));
app.get('/defaults', (req, res) => {
res.send(JSON.stringify(data));
});
app.post('/update', (req, res) => {
lastEntry.next(req.body);
console.log(req.body);
res.send('updated');
});
app.get('/events', (req, res) => {
initialiseSSE(req, res)
});
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
function initialiseSSE(req, res) {
res.set({
"Content-Type": "text/event-stream",
"Cache-Control": "no-cache",
"Connection": "keep-alive",
"Access-Control-Allow-Origin": "*"
});
const lastSub = lastEntry.subscribe(function (message) {
console.log({message});
if (message != null) {
res.write("event: message\n" + "data: " + JSON.stringify(message) + "\n\n");
}
});
const uniqueRequestId = unique();
subscriptions[uniqueRequestId] = {
lastSub
};
res.on('close', () => {
unsubscribe(uniqueRequestId);
});
res.write("retry: 10000\n\n");
}
function unsubscribe(uid) {
console.log('Unsubscribing: ', uid);
subscriptions[uid].lastSub.unsubscribe();
}
function unique() {
// Math.random should be unique because of its seeding algorithm.
// Convert it to base 36 (numbers + letters), and grab the first 9 characters
// after the decimal.
return '_' + Math.random().toString(36).substr(2, 9);
};