Solidity

使用 web3 與 infura 的 websocket 連接出現問題

  • March 18, 2020

我使用 websocket (ws) 連接到 Infura 節點

web3 = new Web3(new Web3.providers.WebsocketProvider ("wss://ropsten.infura.io/ws"));

有時它工作正常,有時它在控制台上給出錯誤:

Error: CONNECTION ERROR: Couldn't connect to node on WS.

Uncaught (in promise) Error: CONNECTION ERROR: Couldn't connect to node on WS.

我不明白為什麼會這樣。

我不想獲得“金鏟子”獎勵或其他東西,但這個問題似乎並不老。我設法成功實現了自動重新連接,因此我想分享程式碼:

首先我創建了一個單獨的函式getProvider

function getProvider() {
 const { WebsocketProvider } = Web3.providers;

 const provider = new WebsocketProvider(WEB3_WEBSOCKET_PROVIDER_URL);

 return new Promise((resolve) => {
   provider.on('connect', () => {
     logger.info('Web3 WS connected.');
     return resolve(provider);
   });

   provider.on('error', () => resolve());
 });
}

然後我有一個listen附加到區塊鏈的函式,以便監聽我感興趣的事件:

async function listen(repositories, wallet) {
 const provider = await getProvider();

 if (!provider) {
   logger.info('Web3 WS unavailable. Reconnecting...');
   setTimeout(() => listen(repositories, wallet), 5000);
   return;
 }

 const web3 = new Web3(provider);

 provider.on('error', (e) => {
   logger.error(`Web3 WS encountered an error: ${e}.`);
   listen(repositories, wallet);
 });

 provider.on('end', () => {
   logger.error('Web3 WS disconnected. Reconnecting...');
   listen(repositories, wallet);
 });

 const contractsConnector = contractsConnectorFactory(web3);
 const contracts = await contractsConnector.connectAll();

 const listeners = listenersFactory(repositories, contracts, wallet);
 listeners.attachAll();
}

這樣,每當連接關閉時,我都可以確保不會錯過同時引發的任何事件。希望能幫助任何有問題的人。

我也遇到過這個問題。我已經能夠(在某種程度上)使用:

   const providerPath = `wss://rinkeby.infura.io/ws`
   web3 = new Web3() 
   const eventProvider = new Web3.providers.WebsocketProvider(providerPath)

   //listen for disconnects
   eventProvider.on('error', e => handleDisconnects(e));
   eventProvider.on('end', e => handleDisconnects(e))

   web3.setProvider(eventProvider)

   function handleDisconnects(e) {
     console.log("error",e);
   }

雖然我無法成功擷取/重新連接

引用自:https://ethereum.stackexchange.com/questions/49082