Skip to content Skip to sidebar Skip to footer

Node-js: Not Receiving Events After Websocket Reconnect

my node-js application uses the bitfinex-api-node npm package to establish a websocket connection to receive data from the Bitfinex crypto-currency exchange. Unfortunately, the co

Solution 1:

The problem is that you don't attach any listeners to a new instance of websocket, when a previous one is closed:

websocket.on('close', ()=>{
    console.log('.on(close) called');
    setTimeout(function() { 
        // this creates a new instance without listeners
        websocket = newBFX().ws(2, opts);
        websocket.open();
    }, 10000);
});

While when you initialize the websocket for the first time, you add them:

websocket.on('open', /* code */);
websocket.onCandle(/* code */);

To resolve the issue, I suggest writing a function that creates and configures a new instance of websocket:

function createWebsocket() {
    const websocket = new BFX().ws(2, opts);
    websocket.on('open', /* code */);
    websocket.onCandle(/* code */);
    websocket.open();
}

And calling it in on('close'):

websocket.on('close', ()=>{
    console.log('.on(close) called');
    setTimeout(createWebsocket, 10000);
});

Post a Comment for "Node-js: Not Receiving Events After Websocket Reconnect"