我正在尝试使用托管 AWS 以太坊节点订阅以太坊区块链。我在这里按照教程进行操作:https ://docs.aws.amazon.com/managed-blockchain/latest/ethereum-dev/ethereum-json-rpc.html(标题为使用 web3.js 进行以太坊 API 调用的部分WebSockets 到托管区块链上的以太坊节点)
一切正常,所以我在 pm2 上启动了该进程,但后来我回来发现 websocket 连接失败并显示以下错误消息:Error: CONNECTION ERROR: The connection got closed with the close code '1001' and the following reason string 'Going away'
处理这个问题的最佳策略是什么?AWS 提供了一个帮助脚本(见下文),但我认为我需要更改此代码以处理 websocket 断开连接。我对 Node 和 websockets 都很陌生,所以我将不胜感激任何指针!
/////////////////////////////////////////////////////
// Authored by Carl Youngblood
// Senior Blockchain Solutions Architect, AWS
// Adapted from web3 npm package v1.3.0
// licensed under GNU Lesser General Public License
// https://github.com/ethereum/web3.js
/////////////////////////////////////////////////////
import AWS from 'aws-sdk';
import WebsocketProvider from 'web3-providers-ws';
import pkg from 'websocket';
const { w3cwebsocket } = pkg;
const Ws = w3cwebsocket;
export default class AWSWebsocketProvider extends WebsocketProvider {
connect() {
const region = process.env.AWS_DEFAULT_REGION || 'us-east-1';
const credentials = new AWS.EnvironmentCredentials('AWS');
const host = new URL(this.url).hostname;
const endpoint = new AWS.Endpoint(`https://${host}/`);
const req = new AWS.HttpRequest(endpoint, region);
req.method = 'GET';
req.body = '';
req.headers['host'] = host;
const signer = new AWS.Signers.V4(req, 'managedblockchain');
signer.addAuthorization(credentials, new Date());
const headers = {
'Authorization': req.headers['Authorization'],
'X-Amz-Date': req.headers['X-Amz-Date'],
...this.headers
}
this.connection = new Ws(this.url, this.protocol, undefined, headers, this.requestOptions, this.clientConfig);
this._addSocketListeners();
}
}
这是我的代码,它调用它并订阅区块链
import Web3 from 'web3';
import AWSWebsocketProvider from "./aws-websocket-provider.js";
...
const web3 = new Web3(new AWSWebsocketProvider(endpoint));
var subscription = web3.eth.subscribe('newBlockHeaders', function(error, result) {
if (error) {
console.log(error);
}
else {
analyze(result);
}
});