JavaScript double backslash in WebSocket messages
<p>I'm sending binary data over WebSocket to a Python application. This binary data is decoded by calling <code>struct.unpack("BH", data")</code> on it, requiring a 4-long bytes object.<br>
The problem I'm currently facing is, that all data contains duplicate backslashes, even in <code>arraybuffer</code> 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.</p>

<p>How the data is sent:</p>

<pre class="lang-js prettyprint-override"><code>// this.webSocket.binaryType = "arraybuffer";   
var message = "\\x05\\x00\\x00\\x00"; // escaping required
var buffer = new Int8Array(message.length);
for (var i = 0; i &lt; message.length; i++) {
    buffer[i] = message.charCodeAt(i);
}
this.webSocket.send(buffer.buffer);
</code></pre>

<p>In comparison, this is how said data looks when defined in Python:</p>

<pre class="lang-py prettyprint-override"><code>b'\x05\x00\x00\x00'
</code></pre>

<p>And this is how it looks as a received message:
</p>

<pre><code>b'\\x05\\x00\\x00\\x00'
</code></pre>

<p>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.</p>

<p>You should define the message as bytes and not as string:</p>

<pre><code>var buffer = new Int8Array([5,0,0,0])
this.webSocket.send(buffer.buffer)
</code></pre>

javascript python struct byte