-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
64 lines (57 loc) · 1.42 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
'stricted'
const http = require('http')
const express = require('express')
const socketIO = require('socket.io')
const router = require('./src/v1/router.js')
let app = express()
let server = http.Server(app)
let io = socketIO(server)
let port = process.env.PORT || 3000
// Public folder
app.use(express.static('public/dist'))
// Rest API
router.forEach(route => {
app.get('/v1' + route.path, function (req, res) {
route.method(req.body)
.then(results => res.json(results))
.catch(results => res.status(400).json(results))
})
})
// Socket API
let connections = 0
let players = {}
io.on('connection', (socket) => {
let player = null
connections++
socket.on('update', data => {
if (player && data.username !== player.username) {
delete players[player.username]
}
if (data.username.length >= 1) {
players[data.username] = data
}
player = data
})
socket.on('shoot', data => {
io.emit('shoot', data)
})
socket.on('elimination', data => {
io.emit('elimination', data)
})
socket.on('item', data => {
io.emit('item', data)
})
socket.on('disconnect', () => {
if (player) {
delete players[player.username]
}
connections--
})
})
// Socket broadcast
setInterval(() => io.emit('server', {
time: new Date().toTimeString(),
users: connections,
players: players
}), 5)
server.listen(port, () => console.log(`Listening on http://localhost:${port}`))