0

When I try to connect my React client to Huobi websocket, connection immediately closing.

In nodejs I can connect to Huobi websocket without any configuration.

I've tried at postman and it connects.

Tried at https://www.piesocket.com/websocket-tester but it did throw same error and closed immediately. This is error: huobi websocket error at client

This is the sample code for both nodejs and clientside:

const websocket = new WebSocket("wss://api.huobi.pro/ws");

websocket.onopen = () => {
  console.log("connected");
  subscribe(websocket);
};

2 Answers2

0

Most of the code below comes from this answer to this question which is similar to yours: Client JavaScript Problem in unzipped Gzip data form webSocket

  • Huobi returns a blob of byte data that has to be handled as an array buffer
  • the data is gzipped and so must be then decompressed
  • the JSoN can then be parsed into an object that can be processed
  • Huubi also returns a ping to which it expects a pong in reply otherwise it will close the connection

The code uses / imports fflate which works in browsers and is smaller and faster than other compression libraries.

I've added a little bit of error handling to the code. This could be expanded upon to attempt a reconnect to the web socket on an error or if closed.

More information on handling connections to Huobi websockets can be found in their documentation.

import { gunzip, strFromU8 } from "fflate"

function livePrice_Huobi(chart, symbol = "btcusdt", interval = "1min") {
  const ws = new WebSocket("wss://api.huobi.pro/ws");
  const sub = `market.${symbol}.kline.${interval}`

  ws.onopen = () => {
    ws.send(JSON.stringify({
      "sub": sub
    }))
  }

  ws.onmessage = (event) => {
    // load the blob returned from Huobi as an array buffer
    const fr = new FileReader();
    fr.onload = function() {
      // decompress it
      gunzip(
        new Uint8Array(fr.result),
        function(err, raw) {
          if (err) {
            console.error(err);
            return;
          }
          const data = JSON.parse(strFromU8(raw));

          // heartbeat, keep connection alive, 
          // otherwise Huobi will close the connection
          if (typeof data ? .ping === "number") {
            ws.send(JSON.stringify({
              pong: data.ping
            }))
          } else if (data ? .ch == sub) {
          
            // do something with the data
            
          }
        }
      );
    }
    fr.readAsArrayBuffer(event.data);
  }

  ws.onerror = (e) => console.log(e)
  ws.onclose = (e) => console.log(e)
}
leoplaw
  • 53
  • 7
0

I faced this problem today and found out that the ad blocker extension ("Adblock") in my browser has caused it. I have added the exception rule for the domain huobi.pro and it works now.

THe exception rule added to the "Adblock" extension:

@@||huobi.pro

Figure: Add exception rule to the "Adblock" extension's setting page

Ref: Adblock - Defining exception rules