-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
80 lines (69 loc) · 2.14 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'),
socket = require('socket.io')
const config = require('./config'),
GridStorageManager = require('./GridStorageManager'),
gridTemplates = require('./gridTemplates')
const app = express(),
server = app.listen(config.server.port),
io = socket(server)
const storageManager = new GridStorageManager((error) => {
console.log('Azure Blob error: ')
console.log(error)
}, setupServer)
function setupServer() {
if (!storageManager.isNew) {
console.log('Downloading grid...')
storageManager.download().then((gc) => {
console.log('Download complete!')
grid = gc[0]
config.grid = gc[1]
startServer(...gc)
})
} else {
startServer(new Map(gridTemplates.charmander), config.grid)
}
}
function startServer(grid, metadata) {
let isGridChanged = false
setInterval(() => {
if (isGridChanged) {
console.log('Uploading grid...')
storageManager.upload(grid, metadata).then(() => {
console.log('Upload complete!')
})
isGridChanged = false
}
}, 120 * 1000)
process.on('SIGINT', () => {
handleShutdown(grid, metadata)
})
process.on('SIGTERM', () => {
handleShutdown(grid, metadata)
})
app.use(express.static('public'))
console.log('server is running on PORT: ' + config.server.port)
io.sockets.on('connection', function(socket) {
console.log('new connection: ' + socket.id)
const keys = new Uint32Array(grid.keys())
const values = new Uint8Array(grid.values())
socket.emit('grid', {
keys: Buffer.from(keys.buffer),
values: Buffer.from(values.buffer)
})
socket.on('pixel', function(data) {
isGridChanged = true
const idx = data.idx[0],
color = data.color[0]
color === metadata.initColor ? grid.delete(idx) : grid.set(idx, color)
socket.broadcast.emit('pixel', data) // broadcast to all EXCEPT the current socket
})
})
}
function handleShutdown(grid, metadata) {
console.log('Uploading grid...')
storageManager.upload(grid, metadata).then(() => {
console.log('Upload complete!')
console.log('Shutting down...')
process.exit()
})
}