5

I have a private chain with several nodes. Connecting to only one works fine. However, if this one goes down, I want to connect to one of the other node.

Using web3js 1.0.0 beta 26, according to the documentation, it seems that there is no way to know that you are connected or not to the node unless you try a tx or call and it tells you it fails because a property of web3 is undefined.

So I have been trying to "hack" it and use some trick, but no result so far. Setting a provider will always set your web3 variable to something, even if you could not actually connect to the node.

Here is an example of what I tried:

function getNode() {
    console.log("getting node");
    for (let i = 0; i <= nodeInfo.length - 1; i++) {
        let web3 = new Web3(new Web3.providers.HttpProvider(nodeInfo[i].ip + ':' + nodeInfo[i].port));
        console.log(web3.currentProvider.connected);
        if (web3.currentProvider.connected) {
            console.log("Provider is: " + web3.currentProvider.connect + " at " + i + " loop");
            return web3;
        }
    }
    return null;
}

I also tried using callbacks, checking if eth (or any property of web3) is not undefined or whatever, but I cannot connect to other nodes if the default one if down.

Does someone knows how to check if you actually are really connected to a node or not?

1 Answer 1

5

Try this, it also reconnects to the node. Using web3js@1.0 beta

web3.eth.net.isListening().then((s) => {
    console.log('We\'re still connected to the node');
}).catch((e) => {
    console.log('Lost connection to the node, reconnecting');
    web3.setProvider(your_provider_here);
})

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.