Unable to save a jpeg image at the client end - javascript

I have an image stored at the server end. Whenever client connects to the server, it sends the image through sockets. The received image I am able to display it on canvas, however I am unable to save the received image in the local disk. I am trying to use fs.writeFile(), but maybe I am not sending the right parameters. Any leads to this issue will be helpful. Thank You. [I want implement this as a basic communication client-server].
To optimize it, is there any way can I achieve same operation in a much faster way? Any working code would also he helpful.
//server side js code
var app = require('express')();
var http = require('http').Server(app);
var io = require('socket.io')(http);
var fs = require('fs'); // required for file serving
http.listen(6969, function(){
console.log('listening on port 6969');
});
// trying to serve the image file from the server
io.on('connection', function(socket){
start = new Date().getTime();
console.log(start);
console.log('a user connected');
fs.readFile(__dirname + '/image.jpg', function(err, buf){
socket.emit('image', { image: true, buffer: buf.toString('base64') });
console.log('image file is transmitted');
});
});
<script>
var socket = io("http://139.25.100.101:6969");
var ctx = document.getElementById('canvas_win').getContext('2d');
var fs = require('fs');
socket.on("image", function(info) {
if (info.image) {
var img = new Image();
img.src = 'data:image/jpeg;base64,' + info.buffer;
ctx.drawImage(img, 0, 0);
var end = new Date().getTime();
document.getElementById("demo").innerHTML = end;
fs.writeFile('logo.jpeg', img.src, 'data:image/jpeg;base64,', function(err){
if (err) throw err
console.log('File saved.')
})
}
});

I am very new to this but I think that for a "communication" between 2 entities, both must be able at some point to act as server, hence thenecessity of a php script on both ends.
Clients usually send requests to be processed by the server, so if you need a p2p communication, the client must download a php script to enable it to act as a server....
Again, I am a newbie so I might be (VERY) wrong

Related

How to send data between Node js and javascript in an html file

I am using an eye tracker and I want to create a website that displays this data in real time. I have the eye tracker notifying a Node js server and it provides data really consistently but when I used socket.io to send the data over it was buffering really slowly. I want a way to receive this data in a script in my index.html from the Node js server in real time or as close as possible. Any suggestions?
I have found my solution in socket.io-streams. Here's what I did:
in the app.js:
var ss = require('socket.io-stream');
var Readable = require('stream').Readable;
const io = require('socket.io')(http);
io.of('/data').on('connection', socket => {
var eyeTracker = ...
var listener = {
...
onGazeData:function(gazeData){ //trigger for recieving a gaze location
var s = new Readable()
s._read = function() {};
var stream = ss.createStream();
toSend = gazeData.x + "," + gazeData.y
s.push(toSend);
s.pipe(stream);
ss(socket).emit('gaze',stream);
}
}
eyeTracker.setListener(listener);
});
app.get('/', function (req, res) {
res.sendFile(path.join(__dirname, 'index.html'));
}
and in the index.js (linked to index.html) I put:
var ss = require('socket.io-stream');
$(function(){
var socket = io.connect('http://localhost:3000/data'); //or where ever you are running
socket.on('connect', function() {
ss(socket).on('gaze', function(stream) {
stream.on('data', function(data) {
//do what you want with data
})
})
});
//other parts of script outside of socket
});
This solution was able to keep up with the data being streamed.

Send data to Node.js Clients

I am trying to build a Node.js App to Monitor some Raspberry Pi's.
Since those Raspberries don’t have a static IP, they send an UDP Broadcast every 5 seconds.
I'm able to catch that Broadcast with Node.js, but I'm failing to trigger a new function to notify the Node.js Clients.
I tried WebSockets, ServerSendEvents and Socket.io.
I'm able to use Example Code and they work just fine.
But I'm not Experienced enough to build a function which will send data to the clients.
Node.js App:
// ==============================================================================================================
// ===== Dependencies ===========================================================================================
// ==============================================================================================================
var dgram = require('dgram');
var http = require('http');
var url = require("url");
var path = require("path");
var fs = require("fs");
// ==============================================================================================================
// ===== HTTP Serv ==============================================================================================
// ==============================================================================================================
var server = http.createServer(function(request, response) {
var uri = url.parse(request.url).pathname, filename = path.join(process.cwd(), uri);
var contentTypesByExtension = {
'.html': "text/html",
'.css': "text/css",
'.js': "text/javascript",
'.svg': "image/svg+xml"
};
fs.exists(filename, function(exists) {
if(!exists) {
response.writeHead(404, {"Content-Type": "text/plain"});
response.write("404 Not Found\n");
response.end();
return;
}
if (fs.statSync(filename).isDirectory()) filename += '/index.html';
fs.readFile(filename, "binary", function(err, file) {
if(err) {
response.writeHead(500, {"Content-Type": "text/plain"});
response.write(err + "\n");
response.end();
return;
}
var headers = {};
var contentType = contentTypesByExtension[path.extname(filename)];
if (contentType) headers["Content-Type"] = contentType;
response.writeHead(200, headers);
response.write(file, "binary");
response.end();
});
});
});
// ==============================================================================================================
// ===== HeartBeat Broadcast ====================================================================================
// ==============================================================================================================
var bcast = dgram.createSocket('udp4');
bcast.on('message', function (message) {
console.log("Triggered: UDP Broadcast");
// If UDP Broadcast is received, send message/data to client.
});
bcast.bind(5452, "0.0.0.0");
// ==============================================================================================================
// ===== Start Server ===========================================================================================
// ==============================================================================================================
server.listen(80);
console.log("Static file server running/\nCTRL + C to shutdown");
EDIT:
I think I did not explain myself accurate enough.
I do not want to send a UDP message back.
This UDP Broadcast should fire an (Node.js) event, which should update the html and display the raspberry pi (whom send the UDP Package) as online.
EDIT:
In documentation from official page of nodejs (DOCUMENTATION):
var socket = require('socket.io')(http);
var bcast = dgram.createSocket('udp4');
bcast.bind(5452, "0.0.0.0");
bcast.on('message', function (message, remote) {
////if message is an Object pushed into Buffer////
message = message.toString('utf8');
socket.emit("HTML_Update", message);
//////////////////////////////////Solution for unedited question//////////////////////////
// var msgBuffer = Buffer.from(message.toString(); //creating a buffer //
// bcast.send(msgBuffer, 0, msgBuffer.length, remote.port, remote.address, (err) => { //
// bcast.close(); //
// }); //sending message to remote.address:remote.port (like localhost:23456) //
// //
// **build a function which will send data to the clients** //
//////////////////////////////////Solution for unedited question//////////////////////////
});
"If message is an Object pushed into Buffer" - lets say that one of the RPI turned on and started sending UDP message, what should the message pass to server so server can pass it to display: mac address only because if it sends something You can be sure its on, if it does not send its off simple as that. Also to show that change on client You should initialize TCP sockets on server to pass info to servers web page to update content on html with jquery.
Now here is the HTML java script part (I personally make main.js file and write all java script into it and use import it as src into html). Using jquery in main.js:
$(document).ready(function() {
var time = new Date();
var rpi = {
"list" : ["mac1", "mac2", "mac3"],
"time" : [time.getTime(), time.getTime(), time.getTime()],
"label" : ["label_ID1", "label_ID2", "label_ID3"]};
var socket = io.connect('http://your_server_address:80');
setInterval( function(){
for (var i = 0; i <= 2; i++){
if((rpi.time[i] + 10000) < time.getTime()){
$(rpi.label[i]).text("RPI " + rpi.list[i] + " is DOWN");
}
}
}, 5000);
socket.on("HTML_Update", function(data){
for (var i = 0; i<=2; i++) {
if (data.toString().equals(rpi.list[i])) {
$(rpi.label[i]).text("RPI: "+ rpi.list[i] + " is UP");
rpi.time[i] = time.getTime();
}
}
});
}
If You put text label in html to show if specific rpi is up or down this part of code works in this scheme:
Multiple RPI + Server - RPI sends UDP data with mac to server. Server device is used to receive data and show it on any device as web page and change data if RPI is UP/DOWN.

Net.Socket instances don't go away in NodeJS

I'm trying to recreate the functionality of a hardware serial server with Node and it's actually working, but I'm getting errors from socket instances that have been closed.
Here's a simplified version of the app to show what I'm doing...
var net = require('net');
var SerialPort = require('serialport');
var connectionCounter = 0;
var port = new SerialPort('/dev/ttyUSB0', function () {
var server = net.createServer();
server.on('connection',function(socket) {
connectionCounter++;
var connNumber = connectionCounter;
socket.on('error', function () {
console.log('socket ' + connNumber + ' errored');
});
socket.on('data', function(data) {
port.write(data);
});
port.on('data', function(data) {
socket.write(data);
});
});
server.listen(8887, '127.0.0.1');
}
});
So the first chunk of code that's sent into the 8887 port works fine, and it returns the data back out through the socket. The errors start on the second chunk. In the example, I'm keeping a count of the socket instances and outputting the socket instance number with the error. So as the program runs, the number of sockets instances keeps going up. The most recent instance will eventually handle the data, but I can't figure out what I need to delete to clean up all of the previous socket instances so they'll stop trying to process the incoming data.
I've tried socket.end() and socket.destroy(), but those don't seem to work . Do I need to go as far as deleting the server itself and recreating it?
If anyone ever finds this and cares about what was going wrong, I was setting an event listener on the serialport object every time a new net socket was created. So even though I was deleting the socket every time it was closed, the serialport listener was trying to send data to all of the old deleted sockets. So the solution was to removeListeners from the serialport object upon closing the net socket.
you can use array for storing sockets later on you can delete. this is sample code hope you got the idea
var net = require('net');
var SerialPort = require('serialport');
var connectionCounter = 0;
var mySockets = [];
var port = new SerialPort('/dev/ttyUSB0', function () {
var server = net.createServer();
server.on('connection',function(socket) {
mySockets.push(socket);
connectionCounter++;
var connNumber = connectionCounter;
socket.on('error', function () {
console.log('socket ' + connNumber + ' errored');
});
socket.on('data', function(data) {
port.write(data);
});
port.on('data', function(data) {
socket.write(data);
});
});
server.listen(8887, '127.0.0.1');
}
//get the sockets you want to delete
var s = mySockets.pop();
s = null;
});

Node js working on second or third call

I have written a node.js server which creates a server and prints the output when done with an asynchronous function. While I am able to get the correct output always in the console.log. The same is not getting reflected in my response. Here is my code snippet :-
var request = require('request');
var http = require('http');
var cheerio = require('cheerio');
var url = require('url');
var Curl = require( 'node-libcurl' ).Curl;
var sleep = require('sleep');
isDone = 0;
globalImage = "";
http.createServer(function (req, res) {
res.writeHead(200, {'Content-Type': 'text/plain'});
var url_parts = url.parse(req.url, true);
var query = url_parts.query;
var main_url = query["link"];
if (req.url != '/favicon.ico') {
res.writeHead(200);
if(main_url != undefined ){
var position = parseInt(query["position"]);
// web_scrap()
web_scrap(main_url,position, function(image) {
console.log("Console log : " + image);
globalImage = image;
});
res.write(globalImage);
res.end("HEY");
}
}
else {//For favicon and other requests just write 404s
res.writeHead(404);
res.write('This URL does nothing interesting');
res.end();
}
}).listen(3000, '127.0.0.1');
console.log('Server running at http://127.0.0.1:3000/');
function web_scrap(url, position, callback){
// do something
callback(JSON.stringify(product));
}
Now on starting the server and accessing it in browser with parameters link and position as get, I am getting output on second or third refresh. I am getting perfect output in console.log though !
Can anyone help or guide me in this regard ?
Thanks !
From what I understand, you're loading an image from an external source, asynchronously.
Thus, your function continues to run, even though the load is not finished yet. And as your globalImage is a global variable, once it is loaded, it stays in memory, that's why you get the data after some tries.
Just move your res.write and res.end in the callback function, this way the content will be sent once the image is loaded.
web_scrap(main_url,position, function(image) {
console.log("Console log : " + image);
globalImage = image;
res.write(globalImage);
res.end("HEY");
});
Anyway, except if you want to cache your image, you should not have a globalImage variable, as it would stay in memory even though you would want it to be garbage collected. You can remove the variable and just make this:
web_scrap(main_url,position, function(image) {
console.log("Console log : " + image);
res.write(image);
res.end("HEY");
});

NodeJS Stop listening to a certain port

I want to 'reconnect' to a server with different values and I have this right now.
var server = http.createServer(function(req, res) {
if(url!="close"){
server.on("listening", function () { server.close(); });
var file = engine.files[indexOfMovie];
res.setHeader('Content-Length', file.length);
file.createReadStream().pipe(res);
}
});
server.listen('2020');
So what I need to do is let the listener which is already listening stop when a new server is defined and afterwards start the new server.
How can this be done in NodeJS?

Categories

Resources