I'm looking to connect to a WebSocket Provider, and intermittently I'll get an error saying:

Error: connection not open
[0]     at WebsocketProvider.send 

Does a WebSocket connection contain callback data that I can reference so that I can begin calling functions AFTER my provider has been set?


There are at least two ways to detect and retrieve the status of a Websocket Provider connection. One could be through Web3 Provider events and the other could be by calling the isListening API function.

Consider the following code example websocket.js, written in JavaScript using the web3 library:

const Web3 = require("web3");
const address = "wss://rinkeby.infura.io/ws";
const web3 = new Web3(address);
const provider = web3.currentProvider;
provider.on("connect", function () {
    console.log("Websocket Provider connection established!");
web3.eth.net.isListening(function(error, result) {
    if(error) {
    } else {
        console.log("Websocket Provider connection is listening. Status: " + result);                                                                                       

Running with yarn add web3 && node websocket.js, considering the endpoint is available and connectivity status is positive, results in: Websocket Provider connection established! Websocket Provider connection is listening. Status: true

More detailed error handling could be done by registering to other events such as "error" and "end" via additional provider.on statements.

Hope that helps you :)

Stay super!


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.