diff options
author | MikunoNaka <bokuwakanojogahoshii@yahoo.com> | 2021-08-01 02:09:41 +0530 |
---|---|---|
committer | MikunoNaka <bokuwakanojogahoshii@yahoo.com> | 2021-08-01 02:09:41 +0530 |
commit | 1a40b90e29dc61ed28ad251b49e9175a2215c3d0 (patch) | |
tree | ce5c1c6607c9dc73f721c571697786917627d9e2 /src | |
parent | 4766a5d0caac22453ab99f386d80c6c132407904 (diff) |
added functionality to detect incorrect room code
Diffstat (limited to 'src')
-rw-r--r-- | src/components/MultiplayerGrid.js | 11 | ||||
-rw-r--r-- | src/server/index.js | 23 |
2 files changed, 25 insertions, 9 deletions
diff --git a/src/components/MultiplayerGrid.js b/src/components/MultiplayerGrid.js index 5954afa..7c00f17 100644 --- a/src/components/MultiplayerGrid.js +++ b/src/components/MultiplayerGrid.js @@ -32,6 +32,7 @@ const MultiplayerGrid = (props) => { const setMessage = props.setMessage; const setShowMessage = props.setShowMessage; + // host/join room useEffect(() => { if (isHost) { socket.emit("host"); @@ -41,14 +42,20 @@ const MultiplayerGrid = (props) => { setShowMessage(true); }); - socket.on('user joined', () => { + socket.on("player joined", () => { setMessage("Opponent Joined") setShowMessage(true) setTimeout(() => setShowMessage(false), 3000) }) } else { socket.emit("join", prompt("Enter ID")); - socket.on("join fail", () => alert("join fail")); + + // error if room doesn't exist + socket.on("join failed", () => { + setMessage("Error: room not found") + setShowMessage(true) + setTimeout(() => window.location.reload(), 3000) + }); } }, [isHost, setMessage, setShowMessage]); diff --git a/src/server/index.js b/src/server/index.js index a4c9c5c..5eeff99 100644 --- a/src/server/index.js +++ b/src/server/index.js @@ -12,20 +12,24 @@ const io = require("socket.io")(http, { } }); -// also checks for duplicates -const getCode = () => { - const code = `${Math.floor(1000 + Math.random() * 9000)}`; - +// check if room exists +const checkCode = (code) => { const connectedSockets = []; io.sockets.sockets.forEach( (i) => connectedSockets.push(i) ); + // returns true if room exists return connectedSockets.some( (i) => Array.from(i.rooms)[1] === code - ) ? getCode() : code; + ); } +// generate new room code +// also checks for duplicates +const getCode = (code = `${Math.floor(1000 + Math.random() * 9000)}`) => + checkCode(code) ? getCode : code; + const allEqual = (arr) => arr.includes(2) ? false : arr.every(i => i === arr[0]) @@ -59,8 +63,13 @@ io.on('connection', (socket) => { }); socket.on('join', (code) => { - socket.join(code); - io.to(code).emit('user joined'); + if (checkCode(code)) { + socket.join(code); + io.to(code).emit('player joined'); + } else { + // error if room doesn't exist + socket.emit('join failed') + } }); socket.on('update-remote-data', (data) => { |