1

I like to send a ArrayBuffer from JavaScript to an WebSocket Server, which Returns the Binary back to other Clients in the Network.

My Problem is, that I don't know how to send the ArrayBuffer from JavaScript 1:1 to the Server and from the Server back to the Client.

I tried a simple ByteBuffer, but it sends only one Array Element. Then I tried:

        InputStream arrayIO = new ByteArrayInputStream(payloadIO);
        ByteBuffer bufferIO = ByteBuffer.allocate(payloadIO.length + 1);

        while (arrayIO.available() > 0) {
            bufferIO.put((byte) arrayIO.read());
        }

        for (Session rowIO : sessionsIO.values()) {
            if (rowIO.isOpen()) {
                rowIO.getRemote().sendBytes(bufferIO);
            }
        }

Which gives me:

Buffer [0]
0: 0
offset: (...)
parent: (...)
buffer: (...)
byteLength: (...)
byteOffset: (...)
length: (...)
Symbol(Symbol.toStringTag): (...)
__proto__: Uint8Array

On the JavaScript Part.

2 Answers 2

1

You could convert the bytes to a string list and then parse them back into binary bytes.

class ArrayBufferUtil {
  static toString(buffer) {
    return new Uint8Array(buffer).toString()
  }
  
  static parse(s) {
    return new Uint8Array(
      s.split(',').map(i => parseInt(i, 10))
    ).buffer
  }
}

Test

console.log( ArrayBufferUtil.toString( new ArrayBuffer(8) ))
console.log( ArrayBufferUtil.parse( '0,0,0,0,0,0,0,0' ))
Sign up to request clarification or add additional context in comments.

Comments

0

I fixed it by adding an offset on the Client receiving site. The Server sending an Opcode on the first 4 Bytes (RFC6455).

enter image description here

dataIO.buffer.slice(4)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.