在本文中,我们将学习如何使用 Web3JS 在开发环境中自动处理区块链断开后的重新连接。下述方法适用于Web3JS 1.0.0-beta.35版本,但对于稳定的1.2.*版本同样适用。
问题描述
如果您的团队在开发中使用Web3JS,那么您必须意识到Web3JS中没有内置的重新连接功能,来处理区块链断开或重新启动。因此,通常,当连接断开时,NodeJS服务也需要重新启动才能再次连接到区块链。这不是一个实用的方法。
解决方案
让我们看看如何在NodeJS中优雅地处理区块链断开连接。在Web3JS库中, Provider 对象为我们提供了以下事件
Connect (连接) -建立连接
Error(错误) -提供程序错误
End(结束 ) -提供程序连接已结束状态。
断开连接后,我们可以利用 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
版权声明:项目均采集于互联网, 空投币 无法审核全面,且希望大家能赚钱,请谨慎切勿上当受骗!
温馨提示:★★★天上真会掉馅饼!天道酬勤,都是机会!不错过每个空投糖果!真假难以辨认,尽量0撸!