Pesquisa de site

Como receber dados de ponto flutuante via websocket em TypeScript


Eu entendo que não há uma maneira fácil de enviar e receber floats da mesma forma que há para strings. No entanto, se eu configurar meu websocket assim:

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

Devo ser capaz de converter os bytestrings recebidos em floats. Converter floats em bytestrings e enviá-los no lado do servidor é fácil.

A coisa mais próxima que consegui encontrar de uma resposta foi esta. No entanto, descobri que e.target.result está indefinido. Tentei apenas usar e.target, mas o compilador gerou um erro de tipo que não consegui descobrir como corrigir.

Também existem questões como essa, que convertem arrays uint em floats. Mas se eu tiver algo assim

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

Eu preciso entender como trabalhar com event.data quando não é apenas uma string como é aqui.

Resposta #1

Depois de adaptar esta resposta e esta resposta, cheguei à seguinte solução:

//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');
};

Artigos relacionados