kanaka/websockify — Issue #32: Most efficient way to read encoded string from websocket
Author: ntenisOT
Created: 2012-03-08 02:20:45+00:00
State: open

Hello kanaka,

Once again thanks for this wonderful plugin.

I use it to transfer Android Mobile Screenshots from a Java Server and through websockify to my browser.

At the moment I have the following configuration.

`Server 1(Intranet):` Java server taking screenshots and sending those images through a socket (base64 encoded strings). Before each screenshot(Base64 String) I send the length of the string.

`Server 2(Webserver):` websockify as middleware between the intranet server 1(not accessible from the Internet) and the user's browser.

`User's webbrowser:` Presenting image by changing the `.scr` of an image.

Until know I finished the whole implementation but I think that I made a mistake, because after some pictures I cannot get the screenshots. It looks similar to your work, noVNC.The code I am using is the following:

ws.on('message', function () {
var arr = ws.rQshiftBytes(ws.rQlen()), str="", chr;

while (arr.length > 0) {
chr = arr.shift();
str += String.fromCharCode(chr);
}
//console.log(str);
//var isnum = /^\d+$/.test(str);
//console.log("{"+str+"}");
if(str.isNumber()){
console.log(str);
console.log("I am here");
numBytes = parseInt(str);
image = "";
}
else {
concatString(str);
}

});

function concatString(str) {
numBytes = numBytes - str.length;
image = image + str;
if(numBytes == 0)
{
msg(image);
image="";
}
}

function msg(str) {
//msgs.innerHTML += str + "\n";
//msgs.scrollTop = msgs.scrollHeight;
//console.log(str);
//console.log(str);

//var ctx = cv.getContext('2d');
//var img = new Image();
//console.log(str);
//img.src = "test.png";
//img.onload = function () {
//	ctx.drawImage(img,0,0);
//}
document.getElementById("img").src = "data:image/jpeg;base64,"+str;
}

As you can see the algorithm that I am using is really simple. First, read the incoming message and if it is an integer save it in a variable `numBytes`. If it is not an integer that means it is a part from the base64 string thus save it and subtract the length of the string from numBytes.

I believe that is completely wrong, because I have a lot of concatenations thus it is extremely slow.

I forgot to mentioned that the base64 string that I pass has a length of 30 - 60 000 characters.

Can you please suggest me something more efficient? For example reading the integer message and then reading the equivalent bytes from the queue? And then deleting those bytes to empty the queue?

Thanks in advance!