我是node.js
和 zmq
的新用户。我必须发送一个138KB的1KB片段文件。
我有一个客户。客户端在konsole args中接收文件的路径,然后服务器读取该文件并发送给客户端。
问题是,当我发送文件时,只发送一个片段。
Q1 :为什么?
Q2 :我该如何解决?
以下是 server
的代码:
var zmq = require("zmq");
var rp = zmq.socket("rep");
var pussh = zmq.socket('push');
var fs = require("fs");
var i = 0, j = 0; // for index of sendings
var size = 0.0;
var file = '';
var buf = new Buffer(1024101024); // Buffer BIG with all the file
var sendingBuff = new Buffer(1024); // Buffer 1KB what it's send to client
rp.bind("tcp://*:8000", function(err) { // REP.bind() rep-req connection
if(err) throw err;
});
pussh.bind("tcp://*:8001", function(err) { // PUSH.bind() push-pull conection
if(err) throw err;
});
rp.on("message",function(msg,err) { // sending function
if(err) throw err;
file = '' + msg;
console.log('I have received: ' + file);
size = getFilesizeInbytes(file); // get the size of the file
buf = fs.readFileSync(file); // get the file in a buffer
while (i < size){ // WHILE(){ the send loop }
if (j < size){
sendingBuff = buf.toString(i,j); // here I have an error after send the file:
// events.js:72 throw er; Unhandled 'error' event
pussh.send(sendingBuff);
i = i + 1024;
j = j + 1024;
}
else{
j = size;
sendingBuff = buf.toString(i,j);
pussh.send(sendingBuff);
i = size + 1;
}
}
pussh.send("ok");
rp.send("ok");
});
function getFilesizeInbytes(filename) { // function what obtains the file size
var stats = fs.statSync(filename);
var fileSizeInBytes = stats["size"];
fileSizeInBytes = fileSizeInBytes;
return fileSizeInBytes;
}
以下是 client
:
var zmq = require("zmq");
var rq = zmq.socket("req");
var pull = zmq.socket('pull');
var argv = process.argv;
var file = argv[2];
var fs = require("fs");
var counter = 0;
var wData = '';
var buffer = new Buffer (1025);
var writeStream = fs.createWriteStream('local');
rq.connect("tcp://127.0.0.1:8000"); // REQ.connect()->REP rep-req connection
pull.connect("tcp://127.0.0.1:8001"); // PULL.connect()->PUSH push-pull connection
rq.send(file); // send the name of the file from the client -> server
rq.on("ok",function(msg){ // when I receive on REQ "ok" ends
console.log('End of task');
rq.end();
});
rq.on("end",function(msg){
process.exit();
});
pull.on("message",function(msg) {
console.log('received: ' + ++counter); // control the name of buffer received
wData = msg.toString(); // convert buffer msg into String
writeStream.write(wData); // write the data
writeStream.on('ok', function () { // when I receive "ok" ends
writeStream.end();
});
});
答案 0 :(得分:0)
如果希望成功.readFileSync()
没有编码特征,您的 buf
会保留以下对象:
<Buffer 54 65 73 74 69 6e 67 20 4e 6f 64 65 2e 6a 73 20 72 65 61 64 46 69 6c 65 28 29>
您开始尝试通过以下指令重新读取 while(){}
-ed循环:
sendingBuff = buf.toString(i,j);
您可能会注意到,初始和&amp;更新的值不是您想要的:
buf.toString( [encoding == 'utf-8'], [start], [end] )
buf.toString( 0, 0 ); // 1st call -- ZERO BYTEs
buf.toString( 1024, 1024 ); // 2nd call -- ZERO BYTEs
buf.toString( 2048, 2048 ); // 3rd call -- ZERO BYTEs
buf.toString( 3072, 3072 ); // 4th call -- ZERO BYTEs