Added a sync option when connecting to peers

Optimises the user join time by not sending the image data multiple times
This commit is contained in:
Mitchell McCaffrey 2020-04-06 14:33:22 +10:00
parent bdc1a7c14d
commit ac9189c606
2 changed files with 19 additions and 12 deletions

View File

@ -14,7 +14,7 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) {
const [peers, setPeers] = useState({}); const [peers, setPeers] = useState({});
useEffect(() => { useEffect(() => {
function addPeer(id, initiator) { function addPeer(id, initiator, sync) {
const peer = new Peer({ initiator, trickle: false }); const peer = new Peer({ initiator, trickle: false });
peer.on("signal", (signal) => { peer.on("signal", (signal) => {
@ -23,6 +23,9 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) {
peer.on("connect", () => { peer.on("connect", () => {
onPeerConnected && onPeerConnected({ id, peer, initiator }); onPeerConnected && onPeerConnected({ id, peer, initiator });
if (sync) {
peer.send({ id: "sync" });
}
}); });
peer.on("dataComplete", (data) => { peer.on("dataComplete", (data) => {
@ -45,7 +48,7 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) {
} }
function handlePartyMemberJoined(id) { function handlePartyMemberJoined(id) {
addPeer(id, false); addPeer(id, false, false);
} }
function handlePartyMemberLeft(id) { function handlePartyMemberLeft(id) {
@ -56,8 +59,10 @@ function useSession(partyId, onPeerConnected, onPeerDisconnected, onPeerData) {
} }
function handleJoinedParty(otherIds) { function handleJoinedParty(otherIds) {
for (let id of otherIds) { for (let [index, id] of otherIds.entries()) {
addPeer(id, true); // Send a sync request to the first member of the party
const sync = index === 0;
addPeer(id, true, sync);
} }
} }

View File

@ -70,17 +70,19 @@ function Game() {
} }
} }
function handlePeerConnected({ peer, initiator }) { function handlePeerConnected({ peer }) {
if (!initiator) {
if (mapSource) {
peer.send({ id: "map", data: mapDataRef.current });
}
peer.send({ id: "tokenEdit", data: mapTokens });
}
peer.send({ id: "nickname", data: { [socket.id]: nickname } }); 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") { if (data.id === "map") {
const blob = new Blob([data.data.file]); const blob = new Blob([data.data.file]);
mapDataRef.current = { ...data.data, file: blob }; mapDataRef.current = { ...data.data, file: blob };