4

I understand that there is no way to easily send and receive floats the same way there is for strings. However, if I setup my websocket like this:

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

I should be able to convert the incoming bytestrings into floats. Converting floats into bytestrings and sending them on the server side is easy.

The closest thing I could find to an answer was this. However, I found that e.target.result is undefined. I tried just using e.target, but the compiler threw a type error that I couldn't figure out how to fix.

There are also questions like this, which convert uint arrays into floats. But if I have something like this

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

I need to understand how to work with event.data when it isn't just a string like it is here.

Eben Kadile
  • 759
  • 4
  • 21

1 Answers1

3

After adapting this answer and this answer, I've come up with the following solution:

//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');
};
Eben Kadile
  • 759
  • 4
  • 21