我们如何处理web3js中的区块链重新连接

在本文中,我们将学习如何使用Web3JS在生产环境中自动处理区块链断开连接。 下述方法适用于Web3JS 1.0.0-beta.35版本,但对于稳定的1.2。*版本也应适用。

问题描述

如果您的团队在生产中使用Web3JS,那么您必须意识到Web3JS中没有内置的重新连接功能来处理区块链断开或重新启动。 因此,通常,当连接断开时,NodeJS服务也需要重新启动才能再次连接到区块链。 这不是一个非常实用的方法。

让我们看看如何在NodeJS中优雅地处理区块链断开连接。 在Web3JS库中, Provider对象为我们提供了以下事件

  1. 连接 -建立连接
  2. 错误 -提供程序错误
  3. 结束 -提供程序连接已结束。

断开连接后,我们可以利用end事件重新启动新的Web3JS连接。 让我们看一个例子来理解这一点:

文件connection.js

在此文件中,我们将处理NodeJS和区块链之间的连接。 我们将有一个newBlockchainconnection方法,该方法将返回Web3活动连接对象。

const web3 = require ( "web3" ); 
let hasProviderEnded = false , web3Instance, reconnectInterval = 10000 ;  
 
async function newBlockchainConnection ( webSocketProvider, endCallback )  {  
 
        // create new provider 
        const provider = new web3.providers.WebsocketProvider(webSocketProvider);  
        hasProviderEnded = false ; 
 
        // connect event fires when the connection established successfully. 
        provider.on( 'connect' , () => console .log( "connected to blockchain" )); 
        
        // error event fires whenever there is an error response from blockchain and this event also has an error object and message property of error gives us the specific reason for the error 
        provider.on( 'error' , (err) => console .log(err.message)); 
  
        // end event fires whenever the connection end is detected. So Whenever this event fires we will try to reconnect to blockchain 
        provider.on( 'end' , async (err) => {  
                // handle multiple event calls sent by Web3JS library  
                if (hasProviderEnded) return ;  
   
                // setting hashProviderEnded to true as sometimes the end event is fired multiple times by the provider 
                hasProviderEnded = true ;  
  
                // reset the current provider  
                provider.reset();  
                // removing all the listeners of provider. 
                provider.removeAllListeners( "connect" );  
                provider.removeAllListeners( "error" );  
                provider.removeAllListeners( "end" );  
   
                setTimeout( () => {  
                         // emitting the restart event after some time to allow blockchain to complete startup 
                         // we are listening to this event in the other file and this callback will initialize a new connection 
                          endCallback(); 
                }, reconnectInterval);  
        });  
 
        if (web3Instance == undefined ) web3Instance = new web3(provider);  
        else web3Instance.setProvider(provider);  
        return web3Instance;  
}  
   
module .exports = {  
         newBlockchainConnection  
}

档案app.js

const connection = require ( "connection" ); 
const web3JSConnection;  
 
const endCallback  = async function ( )  {  
        web3JSConnection = await connection.newBlockchainConnection( 'ws://127.0.0.1:8545' , customEvent);  
 });  
   
 async function getWeb3Connection ( )  {  
         if (web3JSConnection == undefined ) web3JSConnection = await connection.newBlockchainConnection( 'ws://127.0.0.1:8545' , endCallback);  
     return web3JSConnection;  
 }  
  
module .exports = {  
        getWeb3Connection  
}

摘要

关于区块链断开连接,当提供商触发“结束”事件时,我们将在超时后触发回调。 然后,该事件依次调用该函数以创建新的区块链连接。

需要注意的几点:

  1. 有时,Web3JS为同一连接断开向您发送多个“结束”事件,因此我们必须检查是否已经处理了一次断开连接事件。
  2. 使用“ setProvider”在web3实例对象中设置新提供者,而不是创建新的web3实例
  3. 重置提供程序并删除活动的侦听器
  4. 重新连接间隔通常必须至少为5秒,重新启动区块链大约需要5秒。

Skeps 这样的许多技术 领先的 公司 都在使用 区块 链开发革命性的产品。 请继续关注,直到我们对这一新时代的技术进行下一次撰写。

https://skeps.com/blog/how-we-handle-blockchain-reconnects-in-web3js

From: https://hackernoon.com/how-we-handle-blockchain-reconnects-in-web3js-t5fu37ik

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
1. 引入web3.js库 需要先在HTML文件引入web3.js库,可以从官方网站下载或者使用CDN链接。 ```html <script src="https://cdn.jsdelivr.net/npm/web3@1.3.0/dist/web3.min.js"></script> ``` 2. 连接到以太坊网络 在JavaScript代码,创建一个`Web3`对象并连接到以太坊网络。 ```js // 连接到以太坊网络 const web3 = new Web3(Web3.givenProvider || "http://localhost:8545"); ``` 其,`Web3.givenProvider`是指网页已经连接了以太坊网络,可以直接使用当前提供商,否则指定一个本地的以太坊节点地址。 3. 加载智能合约ABI和地址 需要加载智能合约的ABI和地址,以便使用web3.js调用智能合约的方法。 ```js // 加载合约ABI和地址 const contractABI = [...]; const contractAddress = '0x...'; const myContract = new web3.eth.Contract(contractABI, contractAddress); ``` 4. 调用智能合约方法 调用智能合约的方法可以使用`myContract.methods`属性,该属性包含了智能合约的所有方法。以调用`get()`方法为例: ```js // 调用合约get()方法 myContract.methods.get().call((error, result) => { if (!error) { console.log(result); } else { console.error(error); } }); ``` 其,`call()`方法表示调用智能合约的读取方法(不改变区块链数据),如果是写入方法需要使用`send()`方法。回调函数返回结果或错误信息。 5. 监听智能合约事件 智能合约的事件可以通过`myContract.events`属性进行监听。以监听`Transfer`事件为例: ```js // 监听Transfer事件 const transferEvents = myContract.events.Transfer(); transferEvents.on('data', (event) => { console.log(event.returnValues); }); transferEvents.on('error', console.error); ``` 以上就是使用web3.js调用智能合约的基本流程。涉及到的概念比较复杂,需要深入学习区块链和以太坊相关知识。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值