websocket - 用js读取 binary websocket

访问量: 214

用下面代码就可以:

1. pako 是js中的解压缩的包(?)

2. 其实挺容易的

<html>
  <head>
    <meta charset=utf-8>
    <script src="https://cdn.jsdelivr.net/pako/1.0.3/pako.min.js"></script>
    <script>
pako = window.pako

ws_server = "wss://websocket.xxx.top/ws"

ws = new WebSocket(ws_server);

// ws.binaryType = 'arraybuffer';
var buffer;

ws.onopen = function(){
  document.write("ws opened: " + ws_server + "<br/>")
  ws.send("ping")
  // 9k

  ws.send('{"subscribe":"real_time_trades·xxxyy·zh"}')
}

ws.onmessage = function (evt) {

    if(evt.data == "pong"){
      document.write(evt.data + "<br/>")
      return;
    }
    var reader = new FileReader();
    reader.readAsArrayBuffer(evt.data);
    reader.addEventListener("loadend", function(e)
    {

      let buffer = pako.inflate(e.target.result, { to: 'string' })
      buffer += "<br/>"
      buffer += "----<hr/>"
      buffer += "<br/>"
      document.write(buffer)
    });
};

    </script>
  </head>
  <body>

  </body>
</html>

订阅/RSS Feed

Subscribe

分类/category