Martin Baum Avatar

Sending and Receiving Binary Data in javascript

Lately I had to realize a client of a binary protocol in the browser. For this purpose, sending and receiving binary data in the browser, even for legacy browsers, was essential. What really surpised me, was the performance of the data exchange.Expecially in environments, where low connectivity or high network load are huge obstacles. Here is my solution:

Receiving

Receiving is done by switching the responseType of the XmlHttpRequest object.

// receive as binary
              var binReq = new XMLHttpRequest();
              binReq.open('GET', 'binary/data/url');
              binReq.responseType = "arraybuffer";
              

Now you will receive an Arraybuffer in the data property in the response handler. In the case of IE9 this is not possible but there is an unusual workaround to receive at least an array of byte integers.

// receiving in IE
              new VBArray(xhrObj.responseBody).toArray();
              
              [76, 67, 120, 27, 177, 0, 255,..........]
              

In combination with a polyfill for the DataView, you might be able to work with network transmitted binary data:

Sending

The usual XMLHttpRequest offers the send method that also may use a typed array Some older browsers require a ArrayBuffer instead of an TypedArray. Chrome might drop an error in this case.

// send as binary - impossible in IE9
              var sendData = new TypedArray(32);
              getMessage(sendData);
              binReq.open('POST', 'binary/data/url');
              binReq.send(sndBuffer);
              

A special case is IE9. This guy is unable to send binary data or at least I still haven’t found any hint on this. There are serveral workarounds like encoding the data manually to base64 or hex encoding.