My ultimate goal is to have video streaming from my laptop to a server. I'm trying to do this with NodeJs on both the laptop and the server. To capture the video on the laptop and save it as a jpg file, I use the OpenCV library. I then read the file and convert it to base64 so that I can send it over the network with Node's Net.socket module. Capture, encode, and send are all ongoing processes.
The server code for sending a single jpg file is as follows:
var cv = require('opencv');
var fs = require('fs');
var net = require('net');
var camera = new cv.VideoCapture(0);
var server = net.createServer();
server.listen('50007', '127.0.0.1');
server.on('connection', function(socket){
camera.read(function(image){
image.save('original.jpg');
fs.readFile('original.jpg', 'base64', function(err, image){
socket.write(image, 'base64', function(){
socket.end();
});
});
});
});
On the client I loop until the FIN is received from the server. Here is the client code:
var net = require('net');
var fs = require('fs');
var client = new net.Socket();
var buffer ='';
client.setEncoding('base64');
client.connect('50007', '127.0.0.1', function(){
console.log('Connecting to server...');
});
client.on('data', function(data){
buffer += data;
});
client.on('end', function(){
var dataBuffer = new Buffer(buffer, 'base64');
fs.writeFile('copy.jpg', dataBuffer, function(err){
if(err){
console.log(err);
}
});
});
The issue is that the complete image does not get transmitted. When I open the copied.jpg file, it always has a piece missing at the bottom.
The purpose in the final version is to send one jpg after another, with a term like 'EndOfFile' used to delimit the end of each 'jpg'. I attempted to do this by inserting the keyword 'EndOfFile' to my base64 encoded image before sending, but this was completely messed up on the receiving end.
Sample Advanced Server:
fs.readFile('original.jpg', 'base64', function(err, image){
image += 'EndOfFile';
socket.write(image, 'base64');
});
On the client side, the loop would look for the keyword in each chunk of data, and if it was found, whatever was in the buffer would be put to file and the buffer would be reset, ready for the next file.
Sample Advanced Client
client.on('data', function(data){
if(data.indexOf('EndOfFile') > 0){
buffer += data.substr(0, data.indexOf('EndOfLine'));
var dataBuffer = new Buffer(buffer, 'base64');
fs.writeFile('copy.jpg', dataBuffer, function(err){
if(err){
console.log(err);
}
});
buffer = '';
} else {
buffer += data;
}
});
I got this to work in Python, so I believe my logic is sound, but I'm not as familiar with NodeJS.
If someone could tell me if this is a reasonable approach and where I could have gone wrong, I'd be grateful.
Thank you so much in advance!