0

I'm sending binary data over WebSocket to a Python application. This binary data is decoded by calling struct.unpack("BH", data") on it, requiring a 4-long bytes object.
The problem I'm currently facing is, that all data contains duplicate backslashes, even in arraybuffer mode and is therefor 16 bytes long. I can't detect the varying size because there is data appended to the back of it (irrelevant for this question) and even if I could, I also couldn't find a way to strip the backslashes in Python.

How the data is sent:

// this.webSocket.binaryType = "arraybuffer";   
var message = "\\x05\\x00\\x00\\x00"; // escaping required
var buffer = new Int8Array(message.length);
for (var i = 0; i < message.length; i++) {
    buffer[i] = message.charCodeAt(i);
}
this.webSocket.send(buffer.buffer);

In comparison, this is how said data looks when defined in Python:

b'\x05\x00\x00\x00'

And this is how it looks as a received message:

b'\\x05\\x00\\x00\\x00'

The ideal solution for this issue would be on the JavaScript-side because I can't really change the implementation of the Python application without breaking Python-based clients.

1 Answers1

1

You should define the message as bytes and not as string:

var buffer = new Int8Array([5,0,0,0])
this.webSocket.send(buffer.buffer)
Daniel
  • 42,087
  • 4
  • 55
  • 81
  • Is `5` equivalent to `"\\x05"`? – guest271314 Oct 19 '16 at 21:14
  • No, "\\x05" are 4 bytes, but 5 is equal to the byte `\x05`. – Daniel Oct 19 '16 at 21:16
  • What do you mean with «format»? This is a string with a backslash, `x` `0` and `5`. – Daniel Oct 19 '16 at 21:35
  • Why are `"\\"` included in original string? Is `"\\x05"` intended to be the literal string `x05`? Why are `\\`, `x`, `0` not included at first element of `Uint8Array`? For example using approach described at http://stackoverflow.com/questions/17204912/javascript-need-functions-to-convert-a-string-containing-binary-to-hex-then-co, `+parseInt("0x05", 16).toString(2)` returns `101`, `String.fromCodePoint(101)` returns `"e"`. Is this not incorrect conversion? Can ask a Question if that would be more appropriate. – guest271314 Oct 19 '16 at 21:44
  • "format" as in is `"\\x05"` intended to be a literal string? Or is `"\\x05"` "binary"? – guest271314 Oct 19 '16 at 21:50
  • 1
    the decimal number 5 as a number to the base of 2 is 101. That is not the decimal number 101. – Daniel Oct 19 '16 at 22:19
  • Been too long since last time looked into boolean algrebra – guest271314 Oct 19 '16 at 23:09