我们如何处理web3js中的区块链重新连接
在本文中,我们将自学如何用于Web3Js自动处置生产环境中的区块链插入。下面叙述的方法限于于Web3Js版本1.0.0-beta.35,但是对于平稳的1.2 *版本也限于。问题叙述如果您的团队在生产中用于Web3Js,那么您必需意识到在Web3Js中没内置的新的连接功能来处置区块链插入或重新启动。因此,一般来说情况下,当相连下降时,必须重新启动NodeJS服务以便再度相连到区块链。
这不是一个很简单的方法。解决方案让我们想到我们如何高雅地处置NodeJS中区块链插入的情况。
在Web3Js库中,程序为我们获取了以下事件相连——创建相连错误——程序错误完结——程序相连完结。断开连接后,我们可以利用中止事件重新启动一个新的Web3Js相连。
让我们来看一个例子来解读这一点:File connection.js在这个文件中,我们将处置NodeJS和区块链之间的相连。我们将有一个新的区块链相连,它将回到一个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 }File app.。
本文关键词:我们,如何,处理,web3js,中的,区块,链,重新,连接,九游会J9
本文来源:九游会J9-www.rxmeiyin.com
同类文章排行
- 有限空间宁静生产在行动宁静治理督查篇(四)
- 以人民为中心建设生态情况
- 为什么互联网产品越来越难做了?
- 王健林又悄悄卖了几家万达广场!保险、信托接
- 生态环境部通报2019年1月全国空气质量状况
- 国产顶级“二次元”IP:三国
- 在人工智能炒热机器人时,也被人把风带进了教
- 九游会J9:马云:风停了死的都是猪;国内五省携号转网正式开启
- 中车时代电气碳化硅器件项目通过科技成果鉴定
- 九游会J9-下一代公司是怎么样的?我们在阿里看到模型
最新资讯文章
- 我们如何处理web3js中的区块链重新连接
- 从iOS10设计指南变化看设计的新趋势
- Intel缘何为ARM代工,新标准能被广泛接受么?|解读
- 今年机器人大热,CES2019新品趋势盘点
- 逃离Oracle的围城,焕发云数据库的新生
- 我国新增11处国家森林公园
- 生态环境部通报2019年1月全国空气质量状况
- 中车时代电气碳化硅器件项目通过科技成果鉴定
- 普渡大学将3D打印引入工程专业教学
- 数据采集系统的功能安全
- 全球首次海上极客大赛GeekPwn“一网打尽”智能领域漏洞
- 九游会J9:马云:风停了死的都是猪;国内五省携号转网正式开启
- 九游会J9-下一代公司是怎么样的?我们在阿里看到模型
- 认真的英语单词怎么读
- 2020中考现代文阅读基础知识及答题花样归类(二)
- 有限空间宁静生产在行动宁静治理督查篇(四)
- 以人民为中心建设生态情况
- 值得买?深入浅出了解量子点显示技术
- AI+医疗何去何从?从四大应用场景揭秘
- 聚积科技锁定公共建筑智能调光照明