首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何在web3连接中使用备份节点?

如何在web3连接中使用备份节点?
EN

Ethereum用户
提问于 2019-03-04 18:26:45
回答 1查看 211关注 0票数 0

  1. node1=运行在端口8545 =>上的电流同步块为2000,and
  2. 运行在端口3545 node2=上的=>电流同步块是latest

当我在另一个页面中使用web3并打印web3对象时,它返回node1的连接,根据我的web3.js文件,它应该返回node2的连接,因为在我的node1中只有2000块同步

我也使用了timeInterval(),但是它没有起作用

代码语言:javascript
运行
复制
-------------------------------web3.js------------------------
var node1='http://localhost:8545'
var node2='http://localhost:3545'

    var Web3 = require('web3');
    var web3 = new Web3(new Web3.providers.HttpProvider((node1));

    if(!web3.isConnected()) {
        web3 = new Web3(new Web3.providers.HttpProvider((node2));
    } 
    else {
        web3.eth.getBlockNumber(function(er,blck){
            if(blck>7300000){
                console.log('==> ETH connection to node1);
            }else{
                web3=undefined
                web3 = new Web3(new Web3.providers.HttpProvider((node2));
                console.log('==> ETH connection to node2);
            }
        });
    }
    web3.eth.getBlockNumber(function(er,block){
      console.log(block,web3) 
      // here code works fine, web3 object is for node2
    }) 
    module.exports = web3;

    --------------------------------------------------

代码语言:javascript
运行
复制
   ----------------------demo.js---------------------
    var web3 = require(./web3);
     web3.eth.getBlockNumber(function(er,block){
          console.log(block,web3) 
          // here code did not work, web3 object is for node1
     }) 
    -----------------------------------------------------
EN

回答 1

Ethereum用户

发布于 2019-03-04 18:35:50

您必须编写一个监视程序来主动监视连接,如果它是活动的或非活动的,那么简单的监视程序可以是一个迭代以检查while状态的isConnected循环。

示例

代码语言:javascript
运行
复制
var web3 = new Web3(new Web3.providers.HttpProvider(NODE));
var interval = setInterval(() => {
  if (!web3.isConnected()) {
    web3 = new Web3(new Web3.providers.HttpProvider(NODE));
  }
}, 2000)

也可以使用timeInterval创建

票数 0
EN
页面原文内容由Ethereum提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://ethereum.stackexchange.com/questions/67909

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档