const WebSocket = require("ws"); function startServer() { const server = new WebSocket.Server({ port: 8080 }); const connections = new Array(); let maxID = 0; console.log("Websocket server is running on port 8080."); server.on("connection", (socket, request) => { const userName = request.url.substring(11); maxID++; const current_connection = { userName: userName, id: maxID, socket: socket, }; socket.on("message", (data) => { console.log("[" + current_connection.id + "] " + data); }); socket.on("close", (code, reason) => { console.log( "[" + current_connection.id + "] Disconnected: [" + code + "] " + reason, ); if (code !== 1008) { for (const conn of connections) { if (conn.id !== current_connection.id) { conn.socket.send(userName + " disconnected"); } } connections.splice(connections.indexOf(current_connection), 1); } }); for (const conn of connections) { if (conn.userName === userName) { socket.close( 1008, 'Username: "' + userName + '" is already taken', ); return; } } socket.send("Welcome " + userName); connections.push(current_connection); if (connections.length === 1) { socket.send(userName + ", you are the only player connected"); } else { socket.send(connections.length + " players are connected"); } for (const conn of connections) { if (conn.userName !== userName) { conn.socket.send(userName + " connected"); } } if (connections.length < 4) { for (const conn of connections) { conn.socket.send( "Waiting for " + (4 - connections.length) + " other players to start the game", ); } } else { for (const conn of connections) { conn.socket.send( "Match will start soon, disconnecting " + conn.userName + " from the lobby", ); conn.socket.close(1000, "Match is starting"); } } }); return server; } module.exports = { startServer, };