I want to run a JavaScript code to ping 4 different IP addresses and then retrieve the packet loss and latency of these ping requests and display them on the page.
How do I do this?
You can't do this from JS. What you could do is this:
client --AJAX-- yourserver --ICMP ping-- targetservers
Make an AJAX request to your server, which will then ping the target servers for you, and return the result in the AJAX result.
Possible caveats:
this tells you whether the target servers are pingable from your server, not from the user's client
so the client won't be able to test hosts its LAN
but you shouldn't let the host check hosts on the server's internal network, if any exist
some hosts may block traffic from certain hosts and not others
you need to limit the ping count per machine:
to avoid the AJAX request from timing out
some site operators can get very upset when you keep pinging their sites all the time
resources
long-running HTTP requests could run into maximum connection limit of your server, check how high it is
many users trying to ping at once might generate suspicious-looking traffic (all ICMP and nothing else)
concurrency - you may wish to pool/cache the up/down status for a few seconds at least, so that multiple clients wishing to ping the same target won't launch a flood of pings
The only method I can think of is loading e.g. an image file from the external server. When that load fails, you "know" the server isn't responding (you actually don't know, because the server could just be blocking you).
Take a look at this example code to see what I mean:
/*note that this is not an ICMP ping - but a simple HTTP request
giving you an idea what you could do . In this simple implementation it has flaws
as Piskvor correctly points out below */
function ping(extServer){
var ImageObject = new Image();
ImageObject.src = "http://"+extServer+"/URL/to-a-known-image.jpg"; //e.g. logo -- mind the caching, maybe use a dynamic querystring
if(ImageObject.height>0){
alert("Ping worked!");
} else {
alert("Ping failed :(");
}
}
I was inspired by the latest comment, so I wrote this quick piece of code.
This is a kind of "HTTP ping" which I think can be quite useful to use along with XMLHttpRequest calls(), for instance to figure out which is the fastest server to use in some case or to collect some rough statistics from the user's internet connexion speed.
This small function is just connecting to an HTTP server on an non-existing URL (that is expected to return a 404), then is measuring the time until the server is answering to the HTTP request, and is doing an average on the cumulated time and the number of iterations.
The requested URL is modified randomely at each call since I've noticed that (probably) some transparent proxies or caching mechanisms where faking results in some cases, giving extra fast answers (faster than ICMP actually which somewhat weird).
Beware to use FQDNs that fit a real HTTP server!
Results will display to a body element with id "result", for instance:
<div id="result"></div>
Function code:
function http_ping(fqdn) {
var NB_ITERATIONS = 4; // number of loop iterations
var MAX_ITERATIONS = 5; // beware: the number of simultaneous XMLHttpRequest is limited by the browser!
var TIME_PERIOD = 1000; // 1000 ms between each ping
var i = 0;
var over_flag = 0;
var time_cumul = 0;
var REQUEST_TIMEOUT = 9000;
var TIMEOUT_ERROR = 0;
document.getElementById('result').innerHTML = "HTTP ping for " + fqdn + "</br>";
var ping_loop = setInterval(function() {
// let's change non-existent URL each time to avoid possible side effect with web proxy-cache software on the line
url = "http://" + fqdn + "/a30Fkezt_77" + Math.random().toString(36).substring(7);
if (i < MAX_ITERATIONS) {
var ping = new XMLHttpRequest();
i++;
ping.seq = i;
over_flag++;
ping.date1 = Date.now();
ping.timeout = REQUEST_TIMEOUT; // it could happen that the request takes a very long time
ping.onreadystatechange = function() { // the request has returned something, let's log it (starting after the first one)
if (ping.readyState == 4 && TIMEOUT_ERROR == 0) {
over_flag--;
if (ping.seq > 1) {
delta_time = Date.now() - ping.date1;
time_cumul += delta_time;
document.getElementById('result').innerHTML += "</br>http_seq=" + (ping.seq-1) + " time=" + delta_time + " ms</br>";
}
}
}
ping.ontimeout = function() {
TIMEOUT_ERROR = 1;
}
ping.open("GET", url, true);
ping.send();
}
if ((i > NB_ITERATIONS) && (over_flag < 1)) { // all requests are passed and have returned
clearInterval(ping_loop);
var avg_time = Math.round(time_cumul / (i - 1));
document.getElementById('result').innerHTML += "</br> Average ping latency on " + (i-1) + " iterations: " + avg_time + "ms </br>";
}
if (TIMEOUT_ERROR == 1) { // timeout: data cannot be accurate
clearInterval(ping_loop);
document.getElementById('result').innerHTML += "<br/> THERE WAS A TIMEOUT ERROR <br/>";
return;
}
}, TIME_PERIOD);
}
For instance, launch with:
fp = new http_ping("www.linux.com.au");
Note that I couldn't find a simple corelation between result figures from this script and the ICMP ping on the corresponding same servers, though HTTP response time seems to be roughly-exponential from ICMP response time. This may be explained by the amount of data that is transfered through the HTTP request which can vary depending on the web server flavour and configuration, obviously the speed of the server itself and probably other reasons.
This is not very good code but I thought it could help and possibly inspire others.
The closest you're going to get to a ping in JS is using AJAX, and retrieving the readystates, status, and headers. Something like this:
url = "<whatever you want to ping>"
ping = new XMLHttpRequest();
ping.onreadystatechange = function(){
document.body.innerHTML += "</br>" + ping.readyState;
if(ping.readyState == 4){
if(ping.status == 200){
result = ping.getAllResponseHeaders();
document.body.innerHTML += "</br>" + result + "</br>";
}
}
}
ping.open("GET", url, true);
ping.send();
Of course you can also put conditions in for different http statuses, and make the output display however you want with descriptions etc, to make it look nicer. More of an http url status checker than a ping, but same idea really. You can always loop it a few times to make it feel more like a ping for you too :)
I've come up with something cause I was bored of searching hours after hours for something that everyone is saying "impossible", only thing I've found was using jQuery.
I've came up with a new simple way using Vanilla JS (nothing else than base JavaScript).
Here's my JSFiddle: https://jsfiddle.net/TheNolle/5qjpmrxg/74/
Basically, I create a variable called "start" which I give the timestamp, then I try to set an invisible image's source to my website (which isn't an image) [can be changed to any website], because it's not an image it creates an error, which I use to execute the second part of the code, at this time i create a new variable called "end" which i give the timestamp from here (which is different from "start"). Afterward, I simply make a substraction (i substract "start" from "end") which gives me the latency that it took to ping this website.
After you have the choice you can store that in a value, paste it on your webpage, paste it in the console, etc.
let pingSpan = document.getElementById('pingSpan');
// Remove all the way to ...
let run;
function start() {
run = true;
pingTest();
}
function stop() {
run = false;
setTimeout(() => {
pingSpan.innerHTML = "Stopped !";
}, 500);
}
// ... here
function pingTest() {
if (run == true) { //Remove line
let pinger = document.getElementById('pingTester');
let start = new Date().getTime();
pinger.setAttribute('src', 'https://www.google.com/');
pinger.onerror = () => {
let end = new Date().getTime();
// Change to whatever you want it to be, I've made it so it displays on the page directly, do whatever you want but keep the "end - start + 'ms'"
pingSpan.innerHTML = end - start + "ms";
}
setTimeout(() => {
pingTest();
}, 1000);
} // Remove this line too
}
body {
background: #1A1A1A;
color: white
}
img {
display: none
}
Ping:
<el id="pingSpan">Waiting</el>
<img id="pingTester">
<br> <br>
<button onclick="start()">
Start Ping Test
</button>
<button onclick="stop()">
Stop
</button>
function ping(url){
new Image().src=url
}
Above pings the given Url.
Generally used for counters / analytics.
It won't encounter failed responses to client(javascript)
I suggest using "head" to request the header only.
xhr.open('head', 'asstes/imgPlain/pixel.txt' + cacheBuster(), true);
and than ask for readystate 2 - HEADERS_RECEIVED send() has been called, and headers and status are available.
xhr.onreadystatechange = function() {
if (xhr.readyState === 2) { ...
Is it possible to ping a server from Javascript?
Should check out the above solution. Pretty slick.
Not mine, obviously, but wanted to make that clear.
You can't PING with Javascript. I created Java servlet that returns a 10x10 pixel green image if alive and a red image if dead. https://github.com/pla1/Misc/blob/master/README.md
Related
I am pretty lazy, I've made a code that is fetching data from the database and then reloading a page on the index every second if something is changing, so it's visible without needing to refresh the page.
What alternative is faster?
function getLowPlayers() {
var httpd;
if (window.XMLHttpRequest) {
httpd = new XMLHttpRequest();
} else if (window.ActiveXObject) {
httpd = new ActiveXObject("Microsoft.XMLHTTP");
}
httpd.onreadystatechange=function()
{
if (httpd.readyState==4 && httpd.status==200)
{
document.getElementById("lowplayers").innerHTML= httpd.responseText;
setTimeout(getLowPlayers, 1000);
}
}
httpd.open("GET", "includes/ajax.php?noCache=" + Math.random(), true);
httpd.send();
}
or this one:
function ajaxCall() {
$.ajax({
url: "ajax.php",
success: (function (result) {
var res = $.parseJSON(result);
var str1 = "<center><img src='https://steamcommunity-a.akamaihd.net/economy/image/";
var str3 = " ' height='60' width='70'/></br>";
var mes = [];
var div = [];
})
})
};
I know that it is a silly solution to do like this, I could setup a socket.io server, but I think it's too much of work.
I understand that with many visitors, the ajax.php file would send way to many queries per second, is that healthy for the database? Or is it fine with todays internet speed and hosting services?
Which one is faster? Or do you guys have any better solution?
The two codes are more or less the same, the first is written in javascript vainlla, and the second is in JQuery and therefore is shorter and simpler.
If I had to decide, I would choose the second code since it is easier to read and maintain.
Regarding the performance between those 2 codes is practically the same, although if there were many connections the option to use ajax would not be very correct since each server request occupies "X" memory that if we are talking about large numbers would mean that the page was will load slowly because of the waiting queues.
So the best idea as you say is to confiure socket.io and try to update the page with calls from the server to customers.
Link to a similar problem that has no answers, but written in C
I'm using NodeJS to parse output from ark-server-tools, which is a layer on top of SteamCMD. What I'd like to do is parse the progress of the update and assign it to a variable, which I'll return as a GET call that the client can use to check progress of the update.
I put the log results of an update into a file to run my code against, which I've put in a PasteBin for brevity.
update.js
app.get('/update', function(req, res) {
var toReturn;
var outputSoFar;
var total;
var startPos;
var endPos = 0;
//var proc = spawn('arkmanager', ['update', '--safe']);
var proc = spawn('./update-log.sh'); //for testing purposes
proc.stdout.on('data', function(data){
outputSoFar += data.toString();
//if server is already updated
if (outputSoFar.indexOf('Your server is already up to date!') !== -1) {
toReturn = 'Server is already up-to-date.';
}
//find update progress
if (outputSoFar.indexOf('progress:') !== -1) {
for(var line in outputSoFar.split('\n')){
console.log('found progress');
startPos = outputSoFar[line].indexOf('progress:', endPos) + 10; //get the value right after progress:_, which should be a number
endPos = outputSoFar[line].indexOf(' (', startPos); // find the end of this value, which is signified by space + (
console.log(outputSoFar[line].substring(startPos, endPos).trim());
updatePercent = outputSoFar[line].substring(startPos, endPos).trim(); //returned to the `checkUpdateProgress` endpoint
}
toReturn = 'Updating...';
}
});
proc.stderr.on('data', function(data){
console.log(data);
});
proc.on('close', function (code, signal) {
res.writeHead(200, {'Content-Type': 'text/plain'});
res.write(JSON.stringify(toReturn));
res.end();
});
}
/*
* Returns progress of an update
*/
app.get('/updateProgress', function(req, res){
console.log('updatePercent: ' + updatePercent);
res.send(JSON.stringify(updatePercent));
});
Couple questions:
1) Is this the best way to architect my RESTful API? One call for the action of updating and another for checking the progress of the update?
2) I'd love a better way to test the function, as echoing the console log returns the data in one piece, as opposed to a data stream. How do I do this?
3) I'm pretty sure the parsing function itself isn't quite right, but I'm having a hard time testing it because of #2.
If you want to take a look at the project in its entirety, here's the repo.
Thanks in advance for your help!
For one of your questions:
Is this the best way to architect my RESTful API? One call for the
action of updating and another for checking the progress of the
update?
As implemented now, I don't think your service can support concurrent requests correctly. updatePercent is a shared global variable. If i hit /update endpoint with a single client, it will start the ./update-log.sh command.
If I request /update again, it will start another update and overwrite the global updateProgress. There doesn't seem to be anything mapping an updatePercent with the correct process
Additionally, there could be serious performance issues to each request spawning a new process. Node might be able to handle hundreds or thousands of concurrent connections using a single thread, but each request is going to spawn a new process, just something to profile
System: Windows 8.1 64bit with binary from the main page, version 2.0
I have a .txt file with 1 URL per line, I read every line and open the page, searching for a specific url.match (changed domain for privacy reasons in the code) - if found,print the found JSON, abort request, unload page.
My .txt file contains 12500 links, for testing purpose I split it into the first 10/100/500 urls.
Problem 1: If I try 10 urls, it prints 9 and uses 40-50% cpu afterwards
Problem 2: If I try 100 urls, it prints 98, uses 40-50% cpu afterwards for whatever reasons, then it crashes after 2-3 minutes.
Problem 3: Same goes for 98 links (it prints 96, uses 40-50% cpu, then crashes too) and for 500 links
TXT-files:
https://www.dropbox.com/s/eeiy12ku5k15226/sitemaps.7z?dl=1
Crash dumps for 98, 100 and 500 links:
https://www.dropbox.com/s/ilvbg8lv1bizjti/Crash%20dumps.7z?dl=1
console.log('Hello, world!');
var fs = require('fs');
var stream = fs.open('100sitemap.txt', 'r');
var line = stream.readLine();
var webPage = require('webpage');
var i = 1;
while(!stream.atEnd() || line != "") {
//console.log(line);
var page = webPage.create();
page.settings.loadImages = false;
page.open(line, function() {});
//console.log("opened " + line);
page.onResourceRequested = function(requestData, request) {
//console.log("BEFORE: " +requestData.url);
var match = requestData.url.match(/example.com\/ac/g)
//console.log("Match: " + match);
//console.log("Line: " + line);
//console.log("Match: " + match);
if (match != null) {
var targetString = decodeURI(JSON.stringify(requestData.url));
var klammerauf = targetString.indexOf("{");
var jsonobjekt = targetString.substr(klammerauf, (targetString.indexOf("}") - klammerauf) + 1);
targetJSON = (decodeURIComponent(jsonobjekt));
console.log(i);
i++;
console.log(targetJSON);
console.log("");
request.abort();
page.close();
}
};
var line = stream.readLine();
}
//console.log("File closed");
//stream.close();
Concurrent Requests
You really shouldn't be loading pages in a loop, because a loop is a synchronous construct whereas page.open() is asynchronous. Doing so, you will experience the problem that memory consumption sky-rockets, because all URLs are opening at the same time. This will be a problem with 20 or more URLs in the list.
Function-level scope
The other problem is that JavaScript has function level scope. That means that even when you define the page variable inside of the while block it is available globally. Since it is defined globally, you get a problem with the asynchronous nature of PhantomJS. The page inside of the page.onResourceRequested function definition is very likely not the same page that was used to open a URL which triggered the callback. See more on that here. A common solution would to use an IIFE to bind the page variable to only one iteration, but you need to rethink your whole approach.
Memory-leak
You also have a memory-leak, because when the URL in the page.onResourceRequested event doesn't match, you're not aborting the request and not cleaning the page instance up. You probably want to do that for all URLs and not just the ones that match your specific regex.
Easy fix
A fast solution would be to define a function that does one iteration and call the next iteration when the current one finished. You can also re-use one page instance for all requests.
var page = webPage.create();
function runOnce(){
if (stream.atEnd()) {
phantom.exit();
return;
}
var url = stream.readLine();
if (url === "") {
phantom.exit();
return;
}
page.open(url, function() {});
page.onResourceRequested = function(requestData, request) {
/**...**/
request.abort();
runOnce();
};
}
runOnce();
I tried to play a bit with node.js and wrote following code (it doesn't make sense, but that does not matter):
var http = require("http"),
sys = require("sys");
sys.puts("Starting...");
var gRes = null;
var cnt = 0;
var srv = http.createServer(function(req, res){
res.writeHeader(200, {"Content-Type": "text/plain"});
gRes = res;
setTimeout(output,1000);
cnt = 0;
}).listen(81);
function output(){
gRes.write("Hello World!");
cnt++;
if(cnt < 10)
setTimeout(output,1000);
else
gRes.end();
}
I know that there are some bad things in it (like using gRes globally), but my question is, why this code is blocking a second request until the first completed?
if I open the url it starts writing "Hello World" 10 times. But if I open it simultaneous in a second tab, one tab waits connecting until the other tab finished writing "Hello World" ten times.
I found nothing which could explain this behaviour.
Surely it's your overwriting of the gRes and cnt variables being used by the first request that's doing it?
[EDIT actually, Chrome won't send two at once, as Shadow Wizard said, but the code as is is seriously broken because each new request will reset the counter, and outstanding requests will never get closed].
Instead of using a global, wrap your output function as a closure within the createServer callback. Then it'll have access to the local res variable at all times.
This code works for me:
var http = require("http"),
sys = require("sys");
sys.puts("Starting...");
var srv = http.createServer(function(req, res){
res.writeHeader(200, {"Content-Type": "text/plain"});
var cnt = 0;
var output = function() {
res.write("Hello World!\n");
if (++cnt < 10) {
setTimeout(output,1000);
} else {
res.end();
}
};
output();
}).listen(81);
Note however that the browser won't render anything until the connection has closed because the relevant headers that tell it to display as it's downloading aren't there. I tested the above using telnet.
I'm not familiar with node.js but do familiar with server side languages in general - when browser send request to the server, the server creates a Session for that request and any additional requests from the same browser (within the session life time) are treated as the same Session.
Probably by design, and for good reason, the requests from same session are handled sequentially, one after the other - only after the server finish handling one request it will start handling the next.
My question is Client time only displayed, But want to display server time every seconds.
function GetCount(ddate,iid){
var date = new Date();
dateNow = date;
// if time is already past
if(amount < 0){
}
// else date is still good
else{
days=0;hours=0;mins=0;secs=0;out="";
amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs
days=Math.floor(amount/86400);//days
amount=amount%86400;
hours=Math.floor(amount/3600);//hours
amount=amount%3600;
mins=Math.floor(amount/60);//minutes
amount=amount%60;
secs=Math.floor(amount);//seconds
document.getElementById(iid).innerHTML=days;
document.getElementById('countbox1').innerHTML=hours;
document.getElementById('countbox2').innerHTML=mins;
document.getElementById('countbox3').innerHTML=secs;
setTimeout(function(){GetCount(ddate,iid)}, 1000);
}
}
If you want to avoid all that network traffic checking the time with the server every second just: (1) have the server pass the time in a way that you store in a JS variable on page load; (2) also store the client time as at page load; (3) use setInterval to update the time (every 1000 milliseconds or as often as you want) by getting current client time minus client time at page load as an offset of server time at page load. (Obviously this will all go wrong if the user updates their PC clock while your page is running, but how many users would do that? And would it be the end of the world if they did?)
If you really want the actual server time every second - why? Seems a bit of a waste of bandwidth for little if any benefit, but if you must do it use Ajax as already suggested. If you're not familiar with Ajax I'd suggest using Google to find some tutorials - if you use JQuery you can do it with only a couple of lines of code. Easy.
Or put your onscreen clock in an IFRAME that repeatedly reloads itself. Just because I sometimes miss the days of IFRAMEs.
If you run into the issue that the server time is different from the client-side clock, I lookup a server time delta in minutes just once, and then I add it to the minutes of a new Date():
var refDateTime = new Date();
refDateTime.setMinutes(refDateTime.getMinutes() + getServerTimeDelta());
// ...
var serverTimeDelta;
function getServerTimeDelta(recalc) {
var xmlHttp;
if (recalc || !serverTimeDelta) {
try {
if (window.XMLHttpRequest) {
xmlHttp = new XMLHttpRequest();
} else {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
} catch(err1) {
//IE
try {
xmlHttp = new ActiveXObject('Msxml2.XMLHTTP');
} catch(err2) { /* swallow it */ }
}
if (xmlHttp) {
xmlHttp.open('HEAD', window.location.href.toString(), false);
xmlHttp.setRequestHeader("Content-Type", "text/html");
xmlHttp.send('');
var serverDateTime = xmlHttp.getResponseHeader("Date");
if (serverDateTime) {
var dateNow = new Date();
var serverDate = new Date(serverDateTime);
var delta = serverDate.getTime() - dateNow.getTime();
// Convert to minutes
serverTimeDelta = parseInt((delta / 60000) + '');
if (!serverTimeDelta) serverTimeDelta = 0.01;
} else {
serverTimeDelta = 0.011; // avoid auto recalc
}
} else {
serverTimeDelta = 0.012;
}
}
return serverTimeDelta;
}
You need your server to supply the time to JavaScript, either on page load or via XMLHttpRequest.
To get the server time from the client side in javascript you will need to make an ajax call.
Do you know how to make that type of call?
You will basically make another page (or web method etc) which displays/returns the time. You will then use a XMLHttpRequest object to make the call and get the result.