Added option on initial connection to decide whether a sync is needed

This commit is contained in:
Mitchell McCaffrey
2020-03-18 14:44:43 +11:00
parent bc93b01a90
commit 25ee35de44
2 changed files with 28 additions and 15 deletions
+17 -7
View File
@@ -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") {
+11 -8
View File
@@ -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 (
<Container>
<Flex p={2} sx={{ justifyContent: "space-between" }}>
<Heading>
{peerId ? peerId : "Loading"}
</Heading>
<Heading>{peerId ? peerId : "Loading"}</Heading>
<Box>
<Input
id="image"