diff --git a/src/helpers/useSession.js b/src/helpers/useSession.js index 2e57e46..113b846 100644 --- a/src/helpers/useSession.js +++ b/src/helpers/useSession.js @@ -1,7 +1,7 @@ import { useEffect, useState } from "react"; import Peer from "peerjs"; -function useSession(onConnectionOpen) { +function useSession(onConnectionOpen, onConnectionSync) { const [peerId, setPeerId] = useState(null); const [peer, setPeer] = useState(null); const [connections, setConnections] = useState({}); @@ -23,10 +23,16 @@ function useSession(onConnectionOpen) { function handleConnection(connection) { connection.on("open", () => { - connection.send({ - id: "sync", - data: Object.keys(connections) - }); + const metadata = connection.metadata; + if (metadata.sync) { + connection.send({ + id: "sync", + data: Object.keys(connections) + }); + if (onConnectionSync) { + onConnectionSync(connection); + } + } addConnection(connection); @@ -63,7 +69,9 @@ function useSession(onConnectionOpen) { if (connectionId in connections) { continue; } - const connection = peer.connect(connectionId); + const connection = peer.connect(connectionId, { + metadata: { sync: false } + }); addConnection(connection); } } @@ -72,7 +80,9 @@ function useSession(onConnectionOpen) { if (connectionId in connections) { return; } - const connection = peer.connect(connectionId); + const connection = peer.connect(connectionId, { + metadata: { sync: true } + }); connection.on("open", () => { connection.on("data", data => { if (data.id === "sync") { diff --git a/src/routes/Game.js b/src/routes/Game.js index 83b1fa5..0a36eda 100644 --- a/src/routes/Game.js +++ b/src/routes/Game.js @@ -15,8 +15,10 @@ import Token from "../components/Token"; function Game() { const [gameId, setGameId] = useContext(GameContext); const handleConnectionOpenCallback = useCallback(handleConnectionOpen); + const handleConnectionSyncCallback = useCallback(handleConnectionSync); const [peer, peerId, connections, connectTo] = useSession( - handleConnectionOpenCallback + handleConnectionOpenCallback, + handleConnectionSyncCallback ); useEffect(() => { @@ -37,10 +39,6 @@ function Game() { } function handleConnectionOpen(connection) { - if (imageSource) { - connection.send({ id: "image", data: imageDataRef.current }); - } - connection.send({ id: "token", data: tokenPosition }); connection.on("data", data => { if (data.id === "image") { const blob = new Blob([data.data]); @@ -53,6 +51,13 @@ function Game() { }); } + function handleConnectionSync(connection) { + if (imageSource) { + connection.send({ id: "image", data: imageDataRef.current }); + } + connection.send({ id: "token", data: tokenPosition }); + } + const [tokenPosition, setTokenPosition] = useState({ x: 0, y: 0 }); function handleTokenDrag(event, data) { @@ -66,9 +71,7 @@ function Game() { return ( - - {peerId ? peerId : "Loading"} - + {peerId ? peerId : "Loading"}