Javascript Server Side Events with C-client Server Program - javascript

Im looking for feasibility of calling C object(for copying a file from client to server) via Javascript Eventsource.
Ex:
I have a C-Client Program which can be executed as below:
./client ip
executing above file will
send a file from client machine to server running at port 8888.
Server will be running at 8888 will receive the file and will write at /folder1/receivedfile.
./server ip
I need to do this in Javascript Event source.
Javascript code example:
if(window.EventSource){
var source =new EventSource("c-object");
}else{
// Result to xhr polling :( xhttprequest
}

It is feasible. Your second line would be something like this:
var source = new EventSource("http://myserver.example.com:8888/c-object");
Your server must be running HTTP protocol, of course. If going down this route, be aware that calling a resource on a different origin will need all the CORS workarounds. In this case the resource is c-object, and the different origin is because of using a different port to where the HTML was served from.
Alternatively you could use Apache, and start c-object as a cgi program. Then it just needs to interact on stdin/stdout.
But, taking a step back, are you sure it is EventSource you want? If you are just trying to send a signal to the server to tell it to copy a file, and not receiving any data, then use a normal AJAX request. SSE is for the server to stream data to the client, one-way, continuously. After the initial connection is made, SSE cannot send anything to the server.

Related

How to handle tcp/ip raw requests and http requests on the same server

I am working on a gps tracking system and have built a server on node js.
This is how the file looks like for reference.
const net = require('net');
const lora_packet = require('lora-packet');
const dataParser = require('./dataParser');
const clients = [];
net.createServer(function(socket) {
socket.name = socket.remoteAddress + ":" + socket.remotePort;
clients.push(socket);
socket.on('data', function(data) {
console.log("Buffer sent by terminal : ");
console.log(data);
const packet = lora_packet.fromWire(data, 'hex');
const str = packet._packet.PHYPayload.toString('hex');
dataParser.parse_data(str, socket);
});
socket.on('end', function() {
clients.splice(clients.indexOf(socket), 1);
//broadcast(socket.name + "has left the cartel.\n");
});
function broadcast(message, sender) {
clients.forEach(function(client) {
if (client === sender) client.write(message + "\nsent\n");
return;
client.write(message);
});
process.stdout.write(message);
}
}).listen(8080);
console.log("cartel is running on the port 8080\n");
This server file handles only requests from the hardware and processes raw tcp/ip requests.
I want the server to handle http requests also and want to incorporate routing feature in the server too for client side applicarions for browser.
1) Is there any way that http requests can also be handled by the same server or should I open another port and deploy an express node js app on that?
2) If I use the same 8080 port for http, how can the routing be achieved?
3) If I use different ports for http and raw tcp/ip, what would be the best way for communication between the two server. The communication between tcp/ip server and http server should happen via socket(sending data dynamically).
From http server using socket, data has to be sent dynamically to browser to update live location
So is the flow right?
Hardware (<---->)TCP/IP server(<--->)Http server(<--->)Browser
If more information is needed to solve the query, I'll provide with that!
Thank you
It's very complicated to try to speak multiple protocols on the same port. It requires some sort of scheme at the beginning of each connection to sample the incoming data and identify which protocol it is and then shunt that connection off to the right code to handle that protocol. I wouldn't suggest it.
It is way, way easier to just open a second server on a different port for an Express server to field your http requests. Very simple. You can do it right in the same app. Because both servers can be in the same app, you can just directly read from one connection and write to the other. There's no need for interprocess communication.
Is there any way that http requests can also be handled by the same server or should I open another port and deploy an express node js app on that?
Open another port. No need to write another app unless you have a specific reason to use two processes. You can put both the plain TCP server and the Express server in the same node.js app.
If I use the same 8080 port for http, how can the routing be achieved?
It's not easy. Not suggest to use the same port for multiple protocols.
If I use different ports for http and raw tcp/ip, what would be the best way for communication between the two server. The communication between tcp/ip server and http server should happen via socket(sending data dynamically).
You can put both servers in the same node.js app and then you can just read/write directly from one to the other with the same code. No need for interprocess communication.
From http server using socket, data has to be sent dynamically to browser to update live location
Sending data dynamically to a browser usually means you want the browser to hold something like a webSocket or socket.io connection to your server so you can then send data to the browser at any time over the existing connection. Otherwise, you would have to "wait" for the browser to request data and then respond with the data when it asks.

Netcat over Javascript

I'm working under one cloud solution, that's allow user to print receipts on ESC/POS printer. So it's actually pretty easy to print on it like
echo "Hello world!" | nc 192.168.1.37 9100
But, I need to do the same with from user's browser. So i've tried like this:
var connection = new WebSocket('ws://IPAddress:Port');
connection.onopen = function () {
connection.send('Ping'); // Send the message 'Ping' to the server
};
And almost done, but WS send whole stack of HTTP headers starts with
GET / HTTP/1.1
...
Is there way to send it without headers? Or other way to send data to printer?
netcat or nc use TCP protocol and it doesn't use header like "POST /1 HTTP/1.1\r\n" like http requests do. You are probably thinking about using net.Socket() and not WebSocket
I do not want to confuse you because you aim to use javascript in browser, but i used net.Socket() successfully with node.js. The point of this comment is, that you aim to establish TCP connection and not WS.
I think that HTTP always starts sending GET and HTTP Headers.
Maybe you can use some old technology like signed Java Applets or Flash.
In addition, you can download a binary file to the client PC to communicate.

How does Electron proxy URLs?

I created a small server which, for now, just outputs the request.url:
const http = require('http');
http.createServer(onRequest).listen(8080);
function onRequest(clientRequest, clientResponse) {
console.log(clientRequest.url);
}
Using the Electron APIs we can set up a proxy: to proxy all the urls through this server.
So, I'm running my server on localhost:8080 and use the --proxy-server http://localhost:8080 to redirect the traffic through my proxy server. This allows me to change some snippets in the HTML and only then render it in Electron.
When I access http://ionicabizau.net the request.url on the server side is http://ionicabizau.net.
How come that we can override the request url in such a way? What does Electron in the background?
First I thought that it just has to do with appending it like this:
http://localhost:8080/http://ionicabizau.net
But actually, that arrives on the server like /http://ionicabizau.net (notice the first slash).
What's the magic that Electron does to change the url of the request object?
When Electron (or anything else) makes an HTTP request, it connects to the target server and port and sends a message like the following:
GET / HTTP/1.1
Host: www.example.com
Most servers interpret this as an HTTP request for the full URL http://www.example.com/. When you specify a proxy server, that affects what server the HTTP client connects to, but it doesn't change the content of the request (so the requested URL is still http://www.example.com/).
So there's really nothing special that Electron needs to do to "override" the request URL... any HTTP client specifies the request URL as part of the message it sends to the server, and this is independent of which server that message is sent to.

Ajax request returning entire script

I have been looking for a solution for this days ago... so basically I have 2 files: index.html and hellonode.js. Index.html has a div with text and a button that is supposed to make a request to hellonode.js when clicked. hellonode.js is supposed to receive requests and send a response to them.
hellonode.js:
var http= require('http');
function onRequest(request, response){
console.log("request has been received");
response.writeHead(200, {"Context-Type": "text/plain"});
response.write("<h1>response here!</h1>");
response.end();
}
http.createServer(onRequest).listen(8888);
console.log("server is running");
here is my index.html:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById('myDiv').innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET", "hellonode.js", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<h2>content</h2>
</div>
<button type="button" onclick="loadXMLDoc()">Your response content should appear here</button>
</body>
</html>
Im using node js and a apache server (the binary version on Apachelounge.com), and put inside the htdocs folder those 2 files and then start my server, so when I access 192.168.0.102 from my other computers, I get the index.html screen. Everything is fine until here. When I click the button and send the request, the response that I receive is the entire javascript code of hellonode.js. Why is that happening? I have a feeling that my hellonode.js isnt even receiving my request, and that the index.html is just reading the hellonode's content and showing it istead of actually sending a request to it. Im new to this server-side stuff. Thanks.
Apache HTTPD is an HTTP server. The JavaScript you have written is also an HTTP server.
You are making the request to Apache HTTP for the file containing JavaScript program.
You should be running the JavaScript program via Node.js (e.g. from the command line of the server) and then using XMLHttpRequest to make the request to http://example.com:8888/
Note, you will then run into this error, so you will need to modify the JavaScript program to include CORS headers in the response. (Or you could use Apache's mod_proxy to let you make the request to Apache and then forward it to the JavaScript server).
This is happening because you are requesting the file hellonode.js using a GET request.
You need to set up and end point which you can send the request to. For example.
You need to setup a node server not an apache one.
You're correct. By sending an XHR request to hellonode.js, it's just sending a request to retrieve the file, and then returning all of the contents of said file.
It looks like what you're trying to do is run a Node server. You're going to need to configure your server to be able to serve the Node app, instead of running it through Apache (unless you want to serve a Node app with Apache).
To do it locally, you should run node hellonode.js, and it will spin up a server using Node, and be able to serve resources like you're expecting.
(Still, in that case, though, sending an XHR request to a file is just going to return the whole file without running it)
Nodejs is not intended to be run with apache. Apache shows your html page properly because it is meant to serve html pages -apart from PHP scripts-, however, is not intended to serve node scripts. So the request is returning your node scripts just as a plain text, like when you request a .css or .js file asset from a web page in the browser.
You must set up a node script explicitly invoking it with the node command:
node hellonode.js
Or in linux:
nodejs hellonode.js
Then, if your request and your server side script are properly coded, nodejs will actually listen to the request and send the proper response.
However, keep in mind that serving pages with node is not as straightforward than with apache, and educate yourself in services like nodemon or pm2 will sure pay you off.
As an example xmlhttp.open("GET", "hellonode.js", true); can be xmlhttp.open("GET", "http://www.thomas-bayer.com/sqlrest/", true);
Once you type in your terminal:
node hellonode.js
the Nodejs server is running on your current directory and hellonode.js file is used to display the result when you browser to : localhost:8888 in other words your hellonode.js file is playing the role of index.php in the classical php application.
To achieve what you want you can use the built-in http module, or use a framework like Expressjs or others.

JavaScript: list files from http

Can i retrieve a list of files that are located in a URI (HTTP Server) from JavaScript? I only find methods that rely in server side scripting (ie, get the list from a php that reads and outputs the file list accessing the filesystem)
If you store that list in a single file or you know all the locations you want to check, you can use an AJAX request on the client side to make a HTTP request and subsequently load data from your own server.
If you are pulling data from a domain that differs from the one serving the page which runs the AJAX request, then you will run into a problem with your "Cross Origin Request" which will likely prevent you from implementing this feature.
In general http not pass files. it pass information.
You send request and receive answer.
For example:
if you go to the site:
http://www.example.com/index.html
the server receive request with route and it decide what to do with it.
The server can response with index.html file but it can response also with a picture file or another information.
if you want you can read the http protocol
https://www.rfc-editor.org/rfc/rfc2616
or in wikipedia
If you want you can save all your data in one json file and request this information from the server. Another way is to use ftp..

Categories

Resources