Utilizing web sockets, I transmit a 4-bit byte array to my JavaScript library. This byte array signifies a number that I want to retrieve back, all within JavaScript. Examples abound for reading a byte array into a string, but finding examples for the reverse scenario has proven challenging.
In my C# code:
public static void SendImage(byte[] blobArray,
byte[] imageArray , string ts)
{
var blobSize = BitConverter.GetBytes(blobArray.Length);
var tsHdr = Encoding.ASCII.GetBytes(ts);
byte[] newPacket = new byte[imageArray.Length + tsHdr.Length + blobArray.Length+4];
Buffer.BlockCopy(tsHdr, 0, newPacket, 0, tsHdr.Length);
Buffer.BlockCopy(blobSize, 0, newPacket, 17, 4);
Buffer.BlockCopy(blobArray, 0, newPacket, tsHdr.Length+4, blobArray.Length);
Buffer.BlockCopy(imageArray, 0, newPacket, tsHdr.Length+4+ blobArray.Length, imageArray.Length);
}
This process passes a timestamp (using 17 bits), followed by 4 bits for the length of the first image. Subsequently, the first image is included, followed by the second image.
To retrieve all this in JavaScript:
ws.onmessage = function (e) {
try {
var ts = String.fromCharCode.apply(String, new Uint8Array(e.data, 0, 17));
var year = ts.substr(0, 4);
var month = ts.substr(4, 2);
var day = ts.substr(6, 2);
var hour = ts.substr(8, 2);
var min = ts.substr(10, 2);
var second = ts.substr(12, 2);
var mil = ts.substr(14, 3);
liveTimeStamp = hour + "-" + min + "-" + second + "-" + mil + " " + day + "/" + month + "/" + year;
var blobLen= e.data.slice(17, 4);
vat img1 = 'data:image/jpeg;base64,' + arrayBufferToBase64(e.data.slice(21, blobLen ));
var img2 = "data:image/jpeg;base64," + arrayBufferToBase64(e.data.slice(21 + blobLen, len - blobLen + 21));
};