【问题标题】:How to receive floating point data over a websocket in typescript如何在打字稿中通过 websocket 接收浮点数据
【发布时间】:2019-05-07 17:03:54
【问题描述】:

我知道没有办法像字符串一样轻松地发送和接收浮点数。但是,如果我这样设置我的 websocket:

ws = new WebSocket(address);
ws.binaryType = 'blob';

我应该能够将传入的字节串转换为浮点数。将浮点数转换为字节串并在服务器端发送它们很容易。

我能找到的最接近答案的是this。但是,我发现 e.target.result 是未定义的。我尝试只使用e.target,但编译器抛出了一个我不知道如何修复的类型错误。

还有this之类的问题,将uint数组转换成浮点数。但是如果我有这样的东西

ws.onmessage = function(event){
  //do something with event.data
}

event.data 不仅仅是像here 这样的字符串时,我需要了解如何使用它。

【问题讨论】:

    标签: typescript websocket floating-point binary-data


    【解决方案1】:

    在适配this answerthis answer之后,我想出了如下解决方案:

    //open the socket and set the data type to blob
    let socket = new WebSocket(address);
    socket.binaryType = 'blob';
    
    //we will store 6 positions at a time
    let positions = new Float32Array(18);
    
    //helpers
    let buffer = new ArrayBuffer(4);
    let view = new DataView(buffer);
    
    //say hello
    socket.onopen = function(){
      socket.send('Hello');
    };
    
    //keep track of where we are in the position array
    let posIndex = 0;
    
    socket.onmessage = function(msg){
      //convert message to Uint8 array
      let bitArray = new Uint8Array(msg.data);
      for(let i = 0; i < 3; i++){
        for(let j = 0; j < 4; j++){
          //set the elements of the DataView equal to the bytes
          view.setUint8(j, bitArray[4*i + j]);
        }
    
        //update the positions
        if(posIndex < 5){
          positions[3*posIndex + i] = view.getFloat32(0);
          posIndex++;
        }
        else positions[15 + i] = view.getFloat32(0);
      }
    
      //this should log the positions as they come in
      paragraph.innerHTML = paragraph.innerHTML + ",("
                          + positions[posIndex] + ","
                          + positions[posIndex + 1] + ","
                          + positions[posIndex + 2] + ")";
    
      //the server won't send another position until it hears from the client
      socket.send('r');
    };
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-05-06
      • 2017-08-10
      相关资源
      最近更新 更多