Skip to content

Commit

Permalink
feat: Allow one heartbeat to fail (short-lived package loss)
Browse files Browse the repository at this point in the history
  • Loading branch information
therealPaulPlay committed Feb 9, 2025
1 parent 03cd737 commit 21e12d2
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 8 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "playpeerjs",
"version": "1.2.9",
"version": "1.3.0",
"description": "WebRTC-based wrapper for creating robust peer-2-peer multiplayer systems with ease.",
"type": "module",
"main": "dist/playpeer.js",
Expand Down
20 changes: 13 additions & 7 deletions src/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -202,9 +202,9 @@ export default class PlayPeer {
return;
}
this.#hostConnections?.forEach((e) => {
if (e[1] < Date.now() - 2000) {
console.warn(WARNING_PREFIX + "Peer did not respond to heartbeat - closing connection.");
this.#triggerEvent("status", "Peer did not respond to heartbeat - closting connection.");
if (e[1] < Date.now() - 2250) {
console.warn(WARNING_PREFIX + "Peer did not send heartbeats - closing connection.");
this.#triggerEvent("status", "Peer did not send heartbeats - closting connection.");
try { e[0]?.close(); } catch (error) {
console.error(ERROR_PREFIX + "Failed to close incoming connection (no heartbeat):", error);
this.#triggerEvent("error", "Failed to close incoming connection (no heartbeat): " + error);
Expand Down Expand Up @@ -338,6 +338,8 @@ export default class PlayPeer {
reject(new Error("Connection attempt for joining room timed out."));
}, 3 * 1000);

let failedHeartbeatAttempts = 0;

this.#outgoingConnection.on("open", () => {
clearTimeout(timeout);
this.#triggerEvent("outgoingPeerConnected", hostId);
Expand All @@ -348,10 +350,13 @@ export default class PlayPeer {
clearInterval(this.#heartbeatSendInterval); // Prevent multiple ones stacking up in case function fires twice or more
this.#heartbeatSendInterval = setInterval(() => {
if (!this.#heartbeatReceived) {
console.warn(WARNING_PREFIX + "Host did not respond to heartbeat - disconnecting from host.");
this.#triggerEvent("status", "Host did not respond to heartbeat - disconnecting from host.");
this.#outgoingConnection?.close();
return;
failedHeartbeatAttempts++;
if (failedHeartbeatAttempts >= 2) {
console.warn(WARNING_PREFIX + "Host did not respond to heartbeat twice - disconnecting from host.");
this.#triggerEvent("status", "Host did not respond to heartbeat twice - disconnecting from host.");
this.#outgoingConnection?.close();
return;
}
}

// Ping host
Expand Down Expand Up @@ -387,6 +392,7 @@ export default class PlayPeer {
break;
case 'heartbeat_response':
this.#heartbeatReceived = true;
failedHeartbeatAttempts = 0;
break;
}
});
Expand Down

0 comments on commit 21e12d2

Please sign in to comment.