0
node.jsを使用して自分のファイル共有アプリケーションを作成しようとしています。私は、送信者コードと受信者コードを書きました。テキストファイルを送信すると動作しますが、.jpgや.mp3などのファイルを送信しようとすると失敗します。問題は受信側でファイルが「破損」として受信されたことにあります。以下は私の送信者コードと受信機のコードがあるnode.jsのtcpを使用して大きなファイルを送信していますが、破損したファイルを受信しています
送信者:
const net = require('net');
const fs = require('fs');
var destAddr = process.argv[2],
destPort = process.argv[3],
sourceFile = process.argv[4];
const client = net.connect(destPort, destAddr, function() {
/*fs.readFile(sourceFile,function(err,data){
\t \t if(data)
\t \t {
\t \t \t if(client.write(data)==true)
\t \t \t {
\t \t \t \t console.log("Data [ size: %d ] written succesfully",data.length);
\t \t \t \t client.destroy();
\t \t \t }
\t \t \t else console.log("Data write failure");
\t \t }
\t \t else
\t \t \t client.write("err");
\t });
\t */
var fileStream = fs.createReadStream(sourceFile);
fileStream.on('error', function(err) {
console.log(err);
});
fileStream.on('open', function() {
fileStream.pipe(client);
});
});
受信機:私はやってい
const net = require('net');
const fs = require('fs');
var fileName = 'receivedfile.' + process.argv[2];
// process.argv[2] is the file extension to be used to write the file to disk at the receiving end;
const options = {
allowHalfOpen: false,
pauseOnConnect: false,
};
var fileCount = 0;
const server = net.createServer(options, function(listener) {
listener.on('data', (data) => {
console.log("Data [ size: %d ] received", data.length);
fs.writeFile(fileName, data, function(err) {
if (err) console.log("Error writing file to disk");
else {
console.log("Write successful");
fileCount++;
console.log("[ Files received =] %d", fileCount);
console.log("Press Ctr+c to exit");
}
});
});
}).listen(8001,() => {
console.log("Client is waiting for the file on port 8001");
});
g間違っている?
「データイベントは、データの様々なサイズの塊で、接続の存続期間中に複数回をトリガすることができます。」つまり、ディスクに書き込まれたファイルは、新しいチャンクによって上書きされ、最終的に完成前に書き込まれた最後のデータだけを含むファイルになります。 – Anirban
@AnirbanAcharyaが正しい! – robertklep