Solvedweb3.js Handle web socket disconnects

Im making an app that monitors a specific addresses' balance, im using Infura's public websocket endpoint and web3@1.0
I often get disconnected and get "Connection not open on send()"
I tried using a set interval that polls web3.eth.net.isListening() that resets the web3 provider, making it to reconnect to the node but in some cases i get Unhandled rejection Error: CONNECTION ERROR: Couldn't connect to node on IPC. and the app crashes. How am i supposed to handle the disconnects and make my app reconnect to the node?

setInterval(function() { web3.eth.net.isListening() .then() .catch(e => { console.log('[ - ] Lost connection to the node, reconnecting'); web3.setProvider(config.infura_ws); app(); // this just subscribes to newBlockHeaders event }) }, interval);

47 Answers

✔️Accepted Answer

You can listen to events from the WebSocketProvider to detect disconnects.

  const provider = new Web3.providers.WebsocketProvider(path);
  provider.on('error', e => console.error('WS Error', e));
  provider.on('end', e => console.error('WS End', e));

Other Answers:

This works for me

const RINKEBY_WSS = "wss://rinkeby.infura.io/ws";
var provider = new Web3.providers.WebsocketProvider(RINKEBY_WSS);
var web3 = new Web3(provider);

provider.on('error', e => console.log('WS Error', e));
provider.on('end', e => {
    console.log('WS closed');
    console.log('Attempting to reconnect...');
    provider = new Web3.providers.WebsocketProvider(RINKEBY_WSS);

    provider.on('connect', function () {
        console.log('WSS Reconnected');
    });
    
    web3.setProvider(provider);
});

@mkhraisha I haven't been able to test this, but I think I had a similar issue that I fixed using ws: instead of wss:

For future devs looking for a solution to keeping a WebSocket connection to Infura alive, this worked for me

const provider = new Web3.providers.WebsocketProvider(
            config.PROVIDER_WS,
            {
                // @ts-ignore
                clientConfig: {
                    keepalive: true,
                    keepaliveInterval: 60000
                }
            }
        );

@ts-ignore is required for TypeScript as the Web3js typings is expecting a string for the clientConfig option which is wrong. The doco for the WebSocketClient used by Web3js also does not properly cover the keepalive config. https://github.com/theturtle32/WebSocket-Node/blob/master/docs/WebSocketClient.md#client-config-options

The WebSocketConnection code with the keepalive config is at https://github.com/theturtle32/WebSocket-Node/blob/574b703ca978709832c6c2f67d6c1de376d432b5/lib/WebSocketConnection.js#L111

Thanks for your solution @naddison36, seems to resolve the auto idle disconnect problem for me.

Otherwise, it seems it does not prevent other disconnect events. To resolve them and thus ensure a connection stability, I'm personally adding reconnect option on the WebsocketProvider :

reconnect: {
  auto: true,
  delay: 1000,
  maxAttempts: 10,
},

which is set to falseby default : https://github.com/ethereum/web3.js/blob/1.x/packages/web3-providers-ws/src/index.js#L45

More Issues: