Add back optionality to session socket to prevent multiple connections

This commit is contained in:
Mitchell McCaffrey 2021-10-28 11:36:26 +11:00
parent 18725f7c72
commit 019ddcbb8c
6 changed files with 31 additions and 32 deletions

View File

@ -15,7 +15,7 @@ export function PartyProvider({ session, children }: PartyProviderProps) {
useEffect(() => { useEffect(() => {
function handleSocketPartyState(partyState: PartyState) { function handleSocketPartyState(partyState: PartyState) {
if (partyState) { if (partyState && session.id) {
const { [session.id]: _, ...otherMembersState } = partyState; const { [session.id]: _, ...otherMembersState } = partyState;
setPartyState(otherMembersState); setPartyState(otherMembersState);
} else { } else {
@ -23,10 +23,10 @@ export function PartyProvider({ session, children }: PartyProviderProps) {
} }
} }
session.socket.on("party_state", handleSocketPartyState); session.socket?.on("party_state", handleSocketPartyState);
return () => { return () => {
session.socket.off("party_state", handleSocketPartyState); session.socket?.off("party_state", handleSocketPartyState);
}; };
}); });

View File

@ -106,13 +106,13 @@ export function PlayerProvider({ session, children }: PlayerProviderProps) {
} }
session.on("status", handleSocketStatus); session.on("status", handleSocketStatus);
session.socket.on("connect", handleSocketConnect); session.socket?.on("connect", handleSocketConnect);
session.socket.io.on("reconnect", handleSocketConnect); session.socket?.io.on("reconnect", handleSocketConnect);
return () => { return () => {
session.off("status", handleSocketStatus); session.off("status", handleSocketStatus);
session.socket.off("connect", handleSocketConnect); session.socket?.off("connect", handleSocketConnect);
session.socket.io.off("reconnect", handleSocketConnect); session.socket?.io.off("reconnect", handleSocketConnect);
}; };
}); });

View File

@ -74,10 +74,10 @@ function useNetworkedState<S extends { readonly [x: string]: any } | null>(
return; return;
} }
const update = { id: debouncedState[partialUpdatesKey], changes }; const update = { id: debouncedState[partialUpdatesKey], changes };
session.socket.emit(`${eventName}_update`, update); session.socket?.emit(`${eventName}_update`, update);
} }
} else { } else {
session.socket.emit(eventName, debouncedState); session.socket?.emit(eventName, debouncedState);
} }
dirtyRef.current = false; dirtyRef.current = false;
forceUpdateRef.current = false; forceUpdateRef.current = false;
@ -112,11 +112,11 @@ function useNetworkedState<S extends { readonly [x: string]: any } | null>(
}); });
} }
session.socket.on(eventName, handleSocketEvent); session.socket?.on(eventName, handleSocketEvent);
session.socket.on(`${eventName}_update`, handleSocketUpdateEvent); session.socket?.on(`${eventName}_update`, handleSocketUpdateEvent);
return () => { return () => {
session.socket.off(eventName, handleSocketEvent); session.socket?.off(eventName, handleSocketEvent);
session.socket.off(`${eventName}_update`, handleSocketUpdateEvent); session.socket?.off(`${eventName}_update`, handleSocketUpdateEvent);
}; };
}, [session.socket, eventName, partialUpdatesKey]); }, [session.socket, eventName, partialUpdatesKey]);

View File

@ -202,12 +202,12 @@ function NetworkedMapAndTokens({ session }: { session: Session }) {
) { ) {
// Clear map before sending new one // Clear map before sending new one
setCurrentMap(null); setCurrentMap(null);
session.socket.emit("map", null); session.socket?.emit("map", null);
setCurrentMapState(newMapState, true, true); setCurrentMapState(newMapState, true, true);
setCurrentMap(newMap); setCurrentMap(newMap);
session.socket.emit("map", newMap); session.socket?.emit("map", newMap);
if (!newMap || !newMapState) { if (!newMap || !newMapState) {
setAssetManifest(null, true, true); setAssetManifest(null, true, true);
@ -395,12 +395,12 @@ function NetworkedMapAndTokens({ session }: { session: Session }) {
session.on("peerData", handlePeerData); session.on("peerData", handlePeerData);
session.on("peerDataProgress", handlePeerDataProgress); session.on("peerDataProgress", handlePeerDataProgress);
session.socket.on("map", handleSocketMap); session.socket?.on("map", handleSocketMap);
return () => { return () => {
session.off("peerData", handlePeerData); session.off("peerData", handlePeerData);
session.off("peerDataProgress", handlePeerDataProgress); session.off("peerDataProgress", handlePeerDataProgress);
session.socket.off("map", handleSocketMap); session.socket?.off("map", handleSocketMap);
}; };
}); });

View File

@ -152,10 +152,10 @@ function NetworkedMapPointer({ session, active }: NetworkedMapPointerProps) {
} }
} }
session.socket.on("player_pointer", handleSocketPlayerPointer); session.socket?.on("player_pointer", handleSocketPlayerPointer);
return () => { return () => {
session.socket.off("player_pointer", handleSocketPlayerPointer); session.socket?.off("player_pointer", handleSocketPlayerPointer);
}; };
}, [session]); }, [session]);

View File

@ -33,7 +33,7 @@ class Session extends EventEmitter {
/** /**
* The socket io connection * The socket io connection
*/ */
socket: Socket; socket?: Socket;
/** /**
* A mapping of socket ids to session peers * A mapping of socket ids to session peers
@ -43,7 +43,7 @@ class Session extends EventEmitter {
peers: Record<string, SessionPeer>; peers: Record<string, SessionPeer>;
get id() { get id() {
return this.socket.id; return this.socket?.id;
} }
_iceServers: RTCIceServer[] = []; _iceServers: RTCIceServer[] = [];
@ -55,12 +55,6 @@ class Session extends EventEmitter {
constructor() { constructor() {
super(); super();
this.peers = {}; this.peers = {};
this.socket = io(process.env.REACT_APP_BROKER_URL!, {
withCredentials: true,
parser: msgParser,
transports: ["websocket"],
autoConnect: process.env.REACT_APP_MAINTENANCE === "false",
});
// Signal connected peers of a closure on refresh // Signal connected peers of a closure on refresh
window.addEventListener("beforeunload", this._handleUnload.bind(this)); window.addEventListener("beforeunload", this._handleUnload.bind(this));
} }
@ -77,6 +71,11 @@ class Session extends EventEmitter {
this.emit("status", "offline"); this.emit("status", "offline");
return; return;
} }
this.socket = io(process.env.REACT_APP_BROKER_URL!, {
withCredentials: true,
parser: msgParser,
transports: ["websocket"],
});
const response = await fetch(process.env.REACT_APP_ICE_SERVERS_URL); const response = await fetch(process.env.REACT_APP_ICE_SERVERS_URL);
if (!response.ok) { if (!response.ok) {
throw Error("Unable to fetch ICE servers"); throw Error("Unable to fetch ICE servers");
@ -102,7 +101,7 @@ class Session extends EventEmitter {
} }
disconnect() { disconnect() {
this.socket.disconnect(); this.socket?.disconnect();
} }
/** /**
@ -191,7 +190,7 @@ class Session extends EventEmitter {
this._gameId = gameId; this._gameId = gameId;
this._password = password; this._password = password;
this.socket.emit( this.socket?.emit(
"join_game", "join_game",
gameId, gameId,
password, password,
@ -224,7 +223,7 @@ class Session extends EventEmitter {
}; };
const handleSignal = (signal: SignalData) => { const handleSignal = (signal: SignalData) => {
this.socket.emit("signal", JSON.stringify({ to: peer.id, signal })); this.socket?.emit("signal", JSON.stringify({ to: peer.id, signal }));
}; };
const handleConnect = () => { const handleConnect = () => {
@ -367,14 +366,14 @@ class Session extends EventEmitter {
} }
_handleSocketReconnect() { _handleSocketReconnect() {
this.socket.sendBuffer = []; if (this.socket) this.socket.sendBuffer = [];
if (this._gameId) { if (this._gameId) {
this.joinGame(this._gameId, this._password); this.joinGame(this._gameId, this._password);
} }
} }
_handleForceUpdate() { _handleForceUpdate() {
this.socket.disconnect(); this.socket?.disconnect();
this.emit("status", "needs_update"); this.emit("status", "needs_update");
} }
} }