-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
163 lines (143 loc) · 5.12 KB
/
server.js
File metadata and controls
163 lines (143 loc) · 5.12 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
const express = require("express");
const WebSocket = require("ws");
const { v4 } = require("uuid");
const room = require("./js/room.js");
const Player = require("./js/player.js");
const app = express();
const PORT = process.env.PORT || 8080;
const server = app.listen(PORT, () => {
console.log("Servidor escutando na porta:", PORT);
});
const wss = new WebSocket.Server({ server });
wss.on("connection", async (socket) => {
socket.isAlive = true;
socket.on("pong", () => socket.isAlive = true);
const uuid = v4();
let player = null;
// Aguardar primeiro pacote do cliente com nome
socket.once("message", async (message) => {
let data;
try {
data = JSON.parse(message.toString());
} catch (e) {
console.warn("Erro de JSON no join inicial.");
return socket.close();
}
if (data.event !== "join" || !data.content?.name) {
return socket.send(JSON.stringify({
event: "error",
content: { msg: "Evento 'join' com nome é obrigatório." }
}));
}
const name = data.content.name;
await room.add(uuid, name);
player = await room.get(uuid);
console.log(`Jogador conectado: ${name} (${uuid})`);
socket.send(JSON.stringify({
event: "joined_server",
content: { msg: "Bem-vindo ao servidor!", uuid }
}));
socket.send(JSON.stringify({
event: "local_player",
content: {
msg: `Você entrou como ${player.name}!`,
player: player.toJSON()
}
}));
// Notificar outros jogadores
wss.clients.forEach((client) => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
event: "new_player",
content: {
msg: `${player.name} entrou no jogo!`,
player: player.toJSON()
}
}));
}
});
// Enviar lista de jogadores existentes
socket.send(JSON.stringify({
event: "external_players",
content: {
msg: "Sincronizando jogadores!",
players: (await room.getAll())
.filter(p => p.uuid !== uuid)
.map(p => p.toJSON())
}
}));
// Processar mensagens normais
socket.on("message", async (message) => {
let data;
try {
data = JSON.parse(message.toString());
} catch (err) {
console.error("Erro ao fazer parse do JSON:", err);
return;
}
switch (data.event) {
case "update": {
await room.update(uuid, data.content);
const update = {
event: "update_player",
content: {
uuid,
...data.content
}
};
wss.clients.forEach((client) => {
if (client !== socket && client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(update));
}
});
break;
}
case "chat": {
const chat = {
event: "new_chat_message",
content: {
uuid,
name: player?.name || "???",
msg: data.content.msg
}
};
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify(chat));
}
});
break;
}
default:
console.warn("Evento desconhecido:", data.event);
break;
}
});
socket.on("close", async () => {
const leaver = await room.get(uuid);
console.log(`${leaver?.name || uuid} desconectado.`);
await room.remove(uuid);
wss.clients.forEach((client) => {
if (client.readyState === WebSocket.OPEN) {
client.send(JSON.stringify({
event: "player_disconnected",
content: {
uuid,
name: leaver?.name || "???",
msg: `${leaver?.name || "Um jogador"} saiu do jogo!`
}
}));
}
});
});
});
});
// Ping para desconectar clientes inativos
const interval = setInterval(() => {
wss.clients.forEach((ws) => {
if (!ws.isAlive) return ws.terminate();
ws.isAlive = false;
ws.ping();
});
}, 15000);
wss.on("close", () => clearInterval(interval));