Prajwal_7 Prajwal_7 - 2 months ago 5
Node.js Question

Why does datatransfer between sockets takes lot of time?

I have implemented a web based client-server system. The goal is to request for an image file to server, through the socket.

Here is my code at client end. [embedded Javascript code]

<a id="downloadLnk" download="new.jpeg" style="color:red">Download as image</a>

var socket = io("ipaddress");
socket.on("image", function(info) {
if (info.image) {
var end1 = new Date().getTime();
document.getElementById("demo1").innerHTML = end1;
var img = new Image();
img.src = 'data:image/jpeg;base64,' + info.buffer;
}

function download() {
this.href = img.src;
};
downloadLnk.addEventListener('click', download, false);
});


And this is the code at server side: [node.js server, express module, fs module]

io.on('connection', function(socket){
var start1 = new Date().getTime();
console.log(start1);

fs.readFile(__dirname + '/aorta-high512.jpg', function(err, buf){
socket.emit('image', { image: true, buffer: buf.toString('base64') });
});
});


I am transferring a 512x512 resolution image of size 88KB and it is taking approximately one second. Similarly for a 259KB file it takes around 1.2s and 2MB file it takes 2.5s. I do not understand why it is taking so much time?
I checked the bandwidth avalable, internet speed of my network in speedtest.net. The download speed is 95.97Mbps and upload speed is 23.30Mbps.

Could you please let me know, why the transfer time of data is so slow? Is there any other method to transfer data in a faster way? I definitely know that 96Mbps is the bandwidth available but still to test I downloaded a 100Mb pdf file from internet it took approximately 12-14s. Looking at this I atleast expect faster transfer of data at the rate of atleast 2-3 Mbps.

Answer

Socket.IO supports sending/receiving binary data, so taking advantage of that will allow you to avoid expensive encoding of data.

Secondly, when generating/using a data URL in browsers you have to be careful about the URL length. Many browsers impose various limits on the maximum size of such data URLs. One possible workaround to this (not including serving the image directly via HTTP GET) could include having the server split the image into a smaller set of images, which you then use with stacked img tags to give the appearance of a single image.