【问题标题】:Node-js: Not receiving events after websocket reconnectNode-js:websocket重新连接后未收到事件
【发布时间】:2018-08-02 14:27:51
【问题描述】:

我的 node-js 应用程序使用 bitfinex-api-node npm 包建立 websocket 连接以从 Bitfinex 加密货币交易所接收数据。

不幸的是,连接在几个小时后静默中断,应用程序停止通过 websocket 接收数据。这似乎是一个已知问题,可能是 bitfinex-api-module 的错误。

现在,我正在尝试通过首先连接 websocket 并订阅一些蜡烛数据来“手动”重新连接。然后调用 websocket.close() 函数来模拟运行时的连接错误。在 on close 函数中,我设置了另一个超时并尝试创建一个新的 BFX() 对象并 open() 它,但 .on(open) 永远不会被调用。

=> 我一定是做错了什么。我的逻辑有错误吗?有没有更好的重新连接方式?

以下代码有效,只需复制粘贴并运行即可查看。 我非常感谢任何提示或提示。

const BFX = require('bitfinex-api-node');

//websocket
const opts = {
  manageCandles: true, 
  transform: true,
  API_KEY: 'hidden',
  API_SECRET: 'hidden',
  ws: {
    autoReconnect: true,
    seqAudit: true,
    packetWDDelay: 10 * 1000
  }
};
var websocket = new BFX().ws(2, opts);

websocket.on('open', () => {
    //websocket.auth.bind(websocket)
    console.log('.on(open) called');
    websocket.subscribeCandles('trade:5m:tBTCUSD')
});

websocket.on('close', ()=>{
    console.log('.on(close) called');
    setTimeout(function() { 
        websocket = new BFX().ws(2, opts);
        websocket.open();
    }, 10000);
});

websocket.onCandle({key: 'trade:5m:tBTCUSD'},(candles) => { 
    console.log(candles[0]);
})

websocket.open();

// this closes the connection after 20 seconds 
//after start for debugging purposes:
setTimeout(function() {         
        websocket.close();
    }, 10000);

【问题讨论】:

  • 顺便说一句,我还尝试重置变量以避免 on.close() 函数中的冲突:“ websocket = null; BFX = null; ”并且还尝试清空需要缓存(尽管我'我还没有知道它是如何精确工作的)删除 require.cache[require.resolve('bitfinex-api-node')];删除 require.cache['bitfinex-api-node'];

标签: javascript node.js websocket


【解决方案1】:

问题在于,当关闭前一个实例时,您没有将任何侦听器附加到 websocket 的新实例:

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

当你第一次初始化 websocket 时,你添加它们:

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

为了解决这个问题,我建议编写一个函数来创建和配置一个新的 websocket 实例:

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

并在on('close') 中调用它:

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

【讨论】:

    猜你喜欢
    • 2017-06-25
    • 2016-03-28
    • 1970-01-01
    • 2017-05-26
    • 2020-11-21
    • 1970-01-01
    • 1970-01-01
    • 2019-10-27
    • 2019-11-03
    相关资源
    最近更新 更多