Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- const { spawn } = require('child_process');
- args = process.argv
- if(args.length < 6) {
- fileName = args[1].split('\\');
- process.stderr.write(`This program needs at least 4 arguments\nIP Port Filename Chunk Count\n\nExample:\n${fileName[fileName.length-1]} 127.0.0.1 25565 test.txt 1\n\n`)
- process.exit();
- }
- downloadIP = args[2];
- negotiatedPort = parseInt(args[3]);
- fileName = args[4];
- chunkCount = parseInt(args[5]);
- let threadCount = 0;
- let threads = {};
- let freeThreads = [];
- let currChunk = 0;
- let chunksReturned = 0;
- threadMaxLimited = 10;
- if(threadMaxLimited > chunkCount-1) {
- threadMaxLimited = chunkCount-1
- }
- let threadMax = threadMaxLimited
- for(let i = 1; i <= threadMax; i++) {
- freeThreads.push(i)
- }
- let iterations = 1;
- goodbye = function(myFinalMessage) {
- if(myFinalMessage === 'change da world') {
- changeDaWorld = spawn(`node`, [`downloadChunk.js`,`${downloadIP}`,`${negotiatedPort}`,`${fileName}`,`${iterations}`], {stdio: ['ignore','ipc','inherit']})
- changeDaWorld .on('data', function(data) {
- if(process.send){
- process.send({chunk:data.chunk, chunk_contents:data.chunk_contents})
- }
- rat = spawn(`node`, [`downloadChunk.js`,`${downloadIP}`,`${negotiatedPort}`,`${fileName}`,`${iterations+1}`], {stdio: ['ignore','ignore','ignore']})
- rat.on('close', function(code) {
- process.exit(code)
- })
- setTimeout(function(){
- rat.kill()
- },400)
- })}
- }
- downloadThread = function () {
- while(threadCount < threadMax) {
- if(chunksReturned >= chunkCount-threadMax+1) {
- threadMax = chunkCount-chunksReturned-1
- }
- if(freeThreads.length >= 0) {
- currChunk = iterations;
- process.stdout.write("[" + '\033[31;1;4m' + freeThreads.toString('latin1') + '\033[0m' + "]" + '\n')
- threads[freeThreads[0]] = spawn(`node`, [`downloadChunk.js`,`${downloadIP}`,`${negotiatedPort}`,`${fileName}`,`${iterations}`], {stdio: ['ignore','ipc','inherit']})
- .on('message', function(data) {
- if(data.toString('latin1').split(',')[0] === 'timeout'.toString('latin1')) {
- process.stdout.write('Timeout! ' + data.toString('latin1').split(',')[1].toString('latin1') + '\n')
- } else {
- if(chunksReturned >= chunkCount) {} else {
- chunksReturned++
- }
- if(process.send){
- if(data) {
- process.send({chunk:data.chunk, chunk_contents:data.chunk_contents})
- }
- }
- if(freeThreads.indexOf(Object.values(threads).indexOf(this)+1) != -1) {
- process.stderr.write('OOPS, WE JUST TRIED TO ADD A THREAD THAT WAS STILL IN USE\n')
- }
- freeThreads.push(Object.values(threads).indexOf(this)+1)
- threadCount--
- }})
- freeThreads.splice(0,1)
- threadCount++
- iterations++
- }}
- if(chunksReturned >= chunkCount-1) {
- return goodbye('change da world')
- } else {
- setTimeout(function() {
- return downloadThread()
- },500)
- }}
- downloadThread()
Advertisement
Add Comment
Please, Sign In to add comment