1

guys. I try to use node.js to create a p2p file sharing application. While downloading a file, it will download the file block by block.

The block size used in the following code is 1KB. But it has a problem, when available sockets number MAX_SOCKET_CNT is set to 30, it will not work.

How to run the code:

First, run node server.js, then, run node client.js, this will download the file named fav.mp3 to fav-local.mp3.

After downloading, try to run diff fav.mp3 fav-local.mp3 to check if the file downloaded completely.

Could you help me to figure out where the problem is?

Any answer or suggestion is welcome. Thanks in advance.

Here is the source code:

server.js

var http = require("http");
var url = require("url");
var fs = require('fs');

function downloadBlock(request, response){
  var urlParts = url.parse(request.url, true);
  var query = urlParts.query;

  if('block_id' in query){
      response.writeHead(200, {"Content-Type": "audio/mpeg"});
      var startHere=parseInt(query["block_id"]);
      var BLOCK_SIZE=1024;
      var currentPosition=startHere*BLOCK_SIZE;
      var readStream = fs.createReadStream('fav.mp3',{start: startHere*BLOCK_SIZE, end:startHere*BLOCK_SIZE+BLOCK_SIZE-1});
      readStream.pipe(response);
  }else{
      response.writeHead(200, {"Content-Type": "text/html"});
      response.write("refused");
      response.end();
      console.log("Warning: not a file block download request...");
  }
}


http.createServer(downloadBlock).listen(8801);
console.log("Server has started. please ensure that the fav.mp3 file(size=439355B) is here.");

client.js

var http = require('http');
var fs = require('fs');

var remoteFile='fav.mp3';
var fileSize=439355;
var localFile='fav-local.mp3';
var totalBlocks=Math.floor((fileSize+1023)/1024);
/**************************************************/
//KEY POINT
var MAX_SOCKET_CNT=totalBlocks; //worked
//var MAX_SOCKET_CNT=30;//not work //????because of  recursive  downloadBlock function????
/*************************************************/
for(var i=0;i<MAX_SOCKET_CNT;++i){
        downloadBlock('127.0.0.1',8801,remoteFile, localFile,i,totalBlocks);
}

function downloadBlock(IP,PORT,remoteFile,localFile,blockID,totalBlocksNum){
        if(blockID >= totalBlocksNum) return;
        var BLOCK_SIZE=1024;
        var file = fs.createWriteStream(localFile,{start: blockID*BLOCK_SIZE});
        var request = http.get("http://localhost:"+PORT+"/download_block?block_id="+blockID, function(response) {
          response.pipe(file);
          file.on('finish', function() {
                var callback=function downloadBlockOver(){
                        console.log("compelete download blockID:"+blockID);
                        var nextBlockID=blockID+MAX_SOCKET_CNT;
                        if(nextBlockID<totalBlocksNum){
                                downloadBlock(IP,PORT,remoteFile,localFile,nextBlockID,totalBlocksNum); //why not this work if MAX_SOCKET_CNT=30???    
                        }
                }
                file.close(callback);
           });
        });
}

2 Answers 2

0

Aha. Finally, I find out the solution. You have to create the file first. Then change the flag of write stream with "r+" before download.

function touchFile(fileName,fileSize){
    var BLOCK_SIZE=1024;
    var totalBlocks=Math.floor((fileSize+BLOCK_SIZE-1)/BLOCK_SIZE);
    var file = fs.createWriteStream(fileName);
    var blockBuffer=new Buffer(BLOCK_SIZE);
    for(var i=0;i<totalBlocks-1;++i){
            file.write(blockBuffer,0, BLOCK_SIZE);
    }
    var leftToFill=new Buffer(fileSize-(totalBlocks-1)*BLOCK_SIZE);
    file.write(leftToFill,0, leftToFill.Length);
    file.end();
}

add the function "touchFile(localFile,fileSize);" before downloadBlock. Then change:

var file = fs.createWriteStream(localFile,{start: blockID*BLOCK_SIZE});

to

var file = fs.createWriteStream(localFile,{start: blockID*BLOCK_SIZE,flags:'r+',autoClose: true});

It will work now.

0

touchFile just work when MAX_SOCKET_CNT==3. The final solution is use node module random-access-file:https://github.com/mafintosh/random-access-file

The client.js code:

var http = require('http');
var fs = require('fs');
var randomAccessFile = require('random-access-file');


var remoteFile='fav.mp3';
var fileSize=439355;
//var fileSize=6000;//363213; //439355;
var localFile='fav-local.mp3';
var totalBlocks=Math.floor((fileSize+1023)/1024);
/**************************************************/
//KEY POINT
//var MAX_SOCKET_CNT=totalBlocks; //worked
var MAX_SOCKET_CNT=20;//worked
/*************************************************/

var file = randomAccessFile('fav-local.mp3');
for(var i=0;i<MAX_SOCKET_CNT;++i){
    downloadBlock('127.0.0.1',8801,remoteFile, localFile,i,totalBlocks);
}
file.close();

function downloadBlock(IP,PORT,remoteFile,localFile,blockID,totalBlocksNum){
    if(blockID >= totalBlocksNum) return;
    var BLOCK_SIZE=1024;
    var chunks=[];
    var request = http.get("http://localhost:"+PORT+"/download_block?block_id="+blockID, function(response) {
      response.on('data', function (chunk) {
        chunks.push(chunk);
      });
      response.on('error', function (e) { 
        console.log('error.......'+e);
      });
      response.on('close', function () { 
        console.log('close ....');
      });
      response.on('end', function () { 
        var dataToProcess=Buffer.concat(chunks);
        console.log('block data size: ' + dataToProcess.length);
        file.write(blockID*BLOCK_SIZE, dataToProcess,
                    function(err) {
                            if(err){
                                    console.log("error in write...");
                            }else{
                                var nextBlockID=blockID+MAX_SOCKET_CNT;
                                if(nextBlockID<totalBlocksNum){
                                        console.log("download next block:"+nextBlockID);
                                        downloadBlock(IP,PORT,remoteFile,localFile,nextBlockID,totalBlocksNum);   
                                }    
                }
                    }
              );
      });
    });
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.