From d4cbd0d171dc18ba60d12ef83e288b66324aa11b Mon Sep 17 00:00:00 2001 From: Justin Starry Date: Mon, 7 Sep 2020 10:24:16 +0800 Subject: [PATCH] fix: use heartbeat to keep ws connection alive (#12079) --- web3.js/src/connection.js | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/web3.js/src/connection.js b/web3.js/src/connection.js index 93c95ba57c..09e8506000 100644 --- a/web3.js/src/connection.js +++ b/web3.js/src/connection.js @@ -1365,7 +1365,7 @@ export type ConfirmedSignatureInfo = { export class Connection { _rpcRequest: RpcRequest; _rpcWebSocket: RpcWebSocketClient; - _rpcWebSocketConnected: boolean = false; + _rpcWebSocketHeartbeat: IntervalID | null = null; _commitment: ?Commitment; _blockhashInfo: { @@ -2669,7 +2669,10 @@ export class Connection { * @private */ _wsOnOpen() { - this._rpcWebSocketConnected = true; + this._rpcWebSocketHeartbeat = setInterval(() => { + // Ping server every 5s to prevent idle timeouts + this._rpcWebSocket.notify('ping').catch(() => {}); + }, 5000); this._updateSubscriptions(); } @@ -2684,7 +2687,8 @@ export class Connection { * @private */ _wsOnClose() { - this._rpcWebSocketConnected = false; + clearInterval(this._rpcWebSocketHeartbeat); + this._rpcWebSocketHeartbeat = null; this._resetSubscriptions(); } @@ -2777,7 +2781,7 @@ export class Connection { return; } - if (!this._rpcWebSocketConnected) { + if (this._rpcWebSocketHeartbeat === null) { this._resetSubscriptions(); this._rpcWebSocket.connect(); return;