I am trying to implement a protocol to send and receive files over socket. The protocol is specified and I can not change that.
I am new to NodeJs, and this is how I am trying to implement that.
I will write a duplex stream, and pipe file into it. Then pipe it into socket to send data.
The confusion comes where I should read this, and where to write that. How to know reading file has finished, and how to tell socket that it is finished. Docs are not very clear to me, and googling added more confusion :)
Any help would be appreciated.
P.S. I will add my own samples when I get home, I just don't have it now.
EDIT
After @MattHarrison's answer, I changed code into this:
var stream = require('stream');
var util = require('util');
var bufferpack = require('bufferpack');
var fs = require('fs');
var net = require('net');
var MyProtocolStream = function () {
this.writtenHeader = false; // have we written the header yet?
stream.Transform.call(this);
};
util.inherits(MyProtocolStream, stream.Transform);
MyProtocolStream.prototype._transform = function (chunk, encoding, callback) {
if (!this.writtenHeader) {
this.push('==== HEADER ====\n'); // if we've not, send the header first
}
// Can this function be interrupted at this very line?
// Then another _transform comes in and pushes its own data to socket
// Corrupted data maybe then?
// How to prevent this behavior? Buffering whole file before sending?
var self = this;
// I put a random timeout to simulate overlapped calls
// Can this happen in real world?
setTimeout(function () {
self.push(chunk); // send the incoming file chunks along as-is
callback();
}, Math.random()*10);
};
MyProtocolStream.prototype._flush = function (callback) {
this.push('==== FOOTER ====\n'); // Just before the stream closes, send footer
callback();
};
var file = '/tmp/a';
var server = net.createServer(function (sck) {
sck.addr = sck.remoteAddress;
console.log('Client connected - ' + sck.addr);
fs.createReadStream('/tmp/a').pipe(new MyProtocolStream()).pipe(sck);
fs.createReadStream('/tmp/b').pipe(new MyProtocolStream()).pipe(sck);
fs.createReadStream('/tmp/c').pipe(new MyProtocolStream()).pipe(sck);
sck.on('close', function () {
console.log('Client disconnected - ' + this.addr);
})
});
server.listen(22333, function () {
console.log('Server started on ' + 22333)
});
See my comments in _transform.