From ac9189c60614daca8340e9a42aa79b85103da552 Mon Sep 17 00:00:00 2001 From: Mitchell McCaffrey Date: Mon, 6 Apr 2020 14:33:22 +1000 Subject: [PATCH] Added a sync option when connecting to peers Optimises the user join time by not sending the image data multiple times --- src/helpers/useSession.js | 13 +++++++++---- src/routes/Game.js | 18 ++++++++++-------- 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/src/helpers/useSession.js b/src/helpers/useSession.js index 21073d1..90f0ac9 100644 --- a/src/helpers/useSession.js +++ b/src/helpers/useSession.js @@ -14,7 +14,7 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) { const [peers, setPeers] = useState({}); useEffect(() => { - function addPeer(id, initiator) { + function addPeer(id, initiator, sync) { const peer = new Peer({ initiator, trickle: false }); peer.on("signal", (signal) => { @@ -23,6 +23,9 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) { peer.on("connect", () => { onPeerConnected && onPeerConnected({ id, peer, initiator }); + if (sync) { + peer.send({ id: "sync" }); + } }); peer.on("dataComplete", (data) => { @@ -45,7 +48,7 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) { } function handlePartyMemberJoined(id) { - addPeer(id, false); + addPeer(id, false, false); } function handlePartyMemberLeft(id) { @@ -56,8 +59,10 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) { } function handleJoinedParty(otherIds) { - for (let id of otherIds) { - addPeer(id, true); + for (let [index, id] of otherIds.entries()) { + // Send a sync request to the first member of the party + const sync = index === 0; + addPeer(id, true, sync); } } diff --git a/src/routes/Game.js b/src/routes/Game.js index d5c35d7..3fb858e 100644 --- a/src/routes/Game.js +++ b/src/routes/Game.js @@ -70,17 +70,19 @@ function Game() { } } - function handlePeerConnected({ peer, initiator }) { - if (!initiator) { - if (mapSource) { - peer.send({ id: "map", data: mapDataRef.current }); - } - peer.send({ id: "tokenEdit", data: mapTokens }); - } + function handlePeerConnected({ peer }) { peer.send({ id: "nickname", data: { [socket.id]: nickname } }); } - function handlePeerData({ data }) { + function handlePeerData({ data, peer }) { + if (data.id === "sync") { + if (mapSource) { + peer.send({ id: "map", data: mapDataRef.current }); + } + if (mapTokens) { + peer.send({ id: "tokenEdit", data: mapTokens }); + } + } if (data.id === "map") { const blob = new Blob([data.data.file]); mapDataRef.current = { ...data.data, file: blob };