Fixed a bug which causes the server to crash when a player that wasn't in a room disconnected. #1

Merged
arne merged 1 commits from :no-room-crash into master 2020-05-18 10:16:34 +02:00
2 changed files with 20 additions and 15 deletions

View File

@ -29,6 +29,7 @@ module.exports = {
"semi": [ "semi": [
"error", "error",
"always" "always"
] ],
"no-mixed-spaces-and-tabs": "off"
} }
}; };

View File

@ -31,23 +31,27 @@ app.get("/", (req, res) => {
io.on("connection", (socket) => { io.on("connection", (socket) => {
// Handle disconnection // Handle disconnection
socket.on("disconnect", () => { socket.on("disconnect", () => {
const room = players[socket.id].room;
delete players[socket.id]; if (players[socket.id]) {
const room = players[socket.id].room;
var playerUpdate = {}; var playerUpdate = {};
if (io.sockets.adapter.rooms[room]) { if (io.sockets.adapter.rooms[room]) {
for (const id in io.sockets.adapter.rooms[room].sockets) { for (const id in io.sockets.adapter.rooms[room].sockets) {
playerUpdate[id] = players[id]; playerUpdate[id] = players[id];
} }
} }
io.in(room).emit("roomUpdate", playerUpdate); io.in(room).emit("roomUpdate", playerUpdate);
console.log(traffic.out + colours.disconnect(`User ${String(socket.id)} disconnected from room ${room}`)); console.log(traffic.out + colours.disconnect(`User ${String(socket.id)} disconnected from room ${room}`));
if (io.sockets.adapter.rooms[room] == undefined) { if (io.sockets.adapter.rooms[room] == undefined) {
console.log(traffic.int + colours.room(`Room ${room} has been deleted due to a lack of players`)); console.log(traffic.int + colours.room(`Room ${room} has been deleted due to a lack of players`));
}
} }
delete players[socket.id];
}); });
// Request identification // Request identification
@ -125,4 +129,4 @@ io.on("connection", (socket) => {
http.listen(port, () => { http.listen(port, () => {
console.log(colours.data(`\nServer ready, listening on port ${port}\n`)); console.log(colours.data(`\nServer ready, listening on port ${port}\n`));
}); });