-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
107 lines (86 loc) · 2.59 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
104
105
106
107
import express from 'express';
import http from 'http';
import socketio from 'socket.io';
import path from 'path';
const app = express();
const server = http.createServer(app);
const sockets = socketio(server);
const gameConfig = {
width: 580,
height: 320,
maxScore: 10,
};
const game = {
players: {},
rooms: {},
match: {},
};
sockets.on('connection', (socket) => {
console.log(`${socket.id} conectado.`);
socket.on('disconnect', () => {
const player = game.players[socket.id];
if (player) {
console.log(`${player.name} desconectou.`);
const playerId = socket.id;
game.players[playerId].disconnected = new Date().getTime();
const timerId = setTimeout(() => {
removePlayer(playerId);
}, 5000);
game.players[playerId].timerId = timerId;
} else {
console.log(`${socket.id} desconectou.`);
}
});
const removePlayer = (playerId) => {
sendMessage(game.players[playerId], 'saiu');
delete game.players[playerId];
refreshPlayers();
};
socket.on('Reconnect', (reconnectedPlayer) => {
console.log('Reconnect', reconnectedPlayer);
const oldSocketId = reconnectedPlayer.socketId;
const existingPlayer = game.players[oldSocketId];
if (existingPlayer) {
clearTimeout(game.players[oldSocketId].timerId);
game.players[socket.id] = {
...existingPlayer,
disconnected: undefined,
socketId: socket.id,
};
delete game.players[oldSocketId];
sendMessage(game.players[socket.id], 'reconectou');
} else {
console.log(`Player ${reconnectedPlayer.name} not found`);
}
refreshPlayers();
});
socket.on('Login', (name) => {
console.log('Login', name);
game.players[socket.id] = { name, socketId: socket.id };
sendMessage(game.players[socket.id], 'entrou');
refreshPlayers();
});
socket.on('SendMessage', (message) => {
sendMessage(game.players[socket.id], message);
});
});
const sendMessage = (player, message) => {
if (player) {
sockets.emit('ReceiveMessage', `${player.name}: ${message}`);
} else {
sockets.emit('ReceiveMessage', `${message}`);
}
};
const refreshPlayers = () => {
sockets.emit('PlayersRefresh', game.players);
};
app.use(express.static(path.resolve()));
app.use(express.static(path.join(path.resolve(), 'build')));
app.get('/ping', function (req, res) {
return res.send('pong');
});
app.get('/*', function (req, res) {
res.sendFile(path.join(path.resolve(), 'build', 'index.html'));
});
const PORT = process.env.PORT || 4000;
server.listen(PORT, () => console.log(`Server rodando na porta ${PORT}!`));