如何在typescript中通过websocket接收浮点数据

如何在typescript中通过websocket接收浮点数据,typescript,websocket,floating-point,binary-data,Typescript,Websocket,Floating Point,Binary Data,我知道没有办法像字符串那样轻松地发送和接收浮动。但是,如果我这样设置websocket: ws = new WebSocket(address); ws.binaryType = 'blob'; 我应该能够将传入的bytestring转换为float。将float转换为bytestring并在服务器端发送它们很容易 我能找到的最接近答案是。但是,我发现e.target.result未定义。我尝试只使用e.target,但编译器抛出了一个类型错误,我不知道如何修复 还有一些问题,例如,如何将ui

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

ws = new WebSocket(address);
ws.binaryType = 'blob';
我应该能够将传入的bytestring转换为float。将float转换为bytestring并在服务器端发送它们很容易

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

还有一些问题,例如,如何将uint数组转换为浮点数。但是如果我有这样的东西

ws.onmessage = function(event){
  //do something with event.data
}
我需要了解如何处理
事件.数据
,当它不仅仅是一个字符串时。

经过调整后,我提出了以下解决方案:

//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');
};
//打开套接字并将数据类型设置为blob
let socket=新的WebSocket(地址);
socket.binaryType='blob';
//我们将一次存储6个位置
let positions=新的浮点数组(18);
//助手
let buffer=new ArrayBuffer(4);
let view=新数据视图(缓冲区);
//打招呼
socket.onopen=函数(){
socket.send('Hello');
};
//跟踪我们在位置阵列中的位置
设posIndex=0;
socket.onmessage=函数(msg){
//将消息转换为Uint8数组
让bitArray=新的Uint8Array(msg.data);
for(设i=0;i<3;i++){
for(设j=0;j<4;j++){
//将DataView的元素设置为字节
view.setUint8(j,位数组[4*i+j]);
}
//更新职位
if(posIndex<5){
positions[3*posIndex+i]=view.getFloat32(0);
posIndex++;
}
else positions[15+i]=view.getFloat32(0);
}
//这应该记录他们进来时的位置
paragration.innerHTML=paragration.innerHTML+,(“
+位置[posIndex]+“,”
+位置[posIndex+1]+“,”
+职位[职位索引+2]+”;
//服务器在收到客户端的消息之前不会发送其他位置
socket.send('r');
};