Added checks for peer availability and fixed peer error handling

This commit is contained in:
Mitchell McCaffrey 2021-01-21 08:44:46 +11:00
parent de3c601bb3
commit e892661016
2 changed files with 20 additions and 6 deletions

View File

@ -119,7 +119,9 @@ class Session extends EventEmitter {
*/ */
sendTo(sessionId, eventId, data, channel) { sendTo(sessionId, eventId, data, channel) {
if (!(sessionId in this.peers)) { if (!(sessionId in this.peers)) {
this._addPeer(sessionId, true); if (!this._addPeer(sessionId, true)) {
return;
}
} }
if (!this.peers[sessionId].ready) { if (!this.peers[sessionId].ready) {
@ -146,7 +148,9 @@ class Session extends EventEmitter {
*/ */
startStreamTo(sessionId, track, stream) { startStreamTo(sessionId, track, stream) {
if (!(sessionId in this.peers)) { if (!(sessionId in this.peers)) {
this._addPeer(sessionId, true); if (!this._addPeer(sessionId, true)) {
return;
}
} }
if (!this.peers[sessionId].ready) { if (!this.peers[sessionId].ready) {
@ -192,6 +196,12 @@ class Session extends EventEmitter {
this.socket.emit("join_game", gameId, password); this.socket.emit("join_game", gameId, password);
} }
/**
* Add a new peer connection
* @param {string} id
* @param {boolean} initiator
* @returns {boolean} True if peer was added successfully
*/
_addPeer(id, initiator) { _addPeer(id, initiator) {
try { try {
const connection = new Connection({ const connection = new Connection({
@ -322,13 +332,15 @@ class Session extends EventEmitter {
peer.connection.on("error", handleError.bind(this)); peer.connection.on("error", handleError.bind(this));
this.peers[id] = peer; this.peers[id] = peer;
return true;
} catch (error) { } catch (error) {
logError(error); logError(error);
this.emit("peerError", { error }); this.emit("peerError", { error });
this.emit("disconnected");
for (let peer of Object.values(this.peers)) { for (let peer of Object.values(this.peers)) {
peer.connection && peer.connection.destroy(); peer.connection && peer.connection.destroy();
} }
return false;
} }
} }
@ -374,7 +386,9 @@ class Session extends EventEmitter {
_handleSignal(data) { _handleSignal(data) {
const { from, signal } = data; const { from, signal } = data;
if (!(from in this.peers)) { if (!(from in this.peers)) {
this._addPeer(from, false); if (!this._addPeer(from, false)) {
return;
}
} }
this.peers[from].connection.signal(signal); this.peers[from].connection.signal(signal);
} }

View File

@ -66,9 +66,9 @@ function Game() {
setPeerError("Unable to connect to party."); setPeerError("Unable to connect to party.");
} }
} }
session.on("error", handlePeerError); session.on("peerError", handlePeerError);
return () => { return () => {
session.off("error", handlePeerError); session.off("peerError", handlePeerError);
}; };
}, [session]); }, [session]);