是否可以从Javascript平台的服务器?

我正在制作一个Web应用程序,要求我检查远程服务器是否在线。 当我从命令行运行它时,我的页面加载时间达到了60秒(对于8个条目,它将随着更多的线性缩放)。

我决定走在用户端ping的路线。 这样,我可以加载页面,并让他们在浏览我的内容时等待“服务器在线”数据。

如果任何人有上述问题的答案,或者如果他们知道一个解决scheme来保持我的网页加载速度,我一定会感激。

我发现有人用非常聪明的使用本地Image对象来完成这个任务。

从他们的来源看,这是主要function(它依赖于其他部分的来源,但是你有这个想法)。

 function Pinger_ping(ip, callback) { if(!this.inUse) { this.inUse = true; this.callback = callback this.ip = ip; var _that = this; this.img = new Image(); this.img.onload = function() {_that.good();}; this.img.onerror = function() {_that.good();}; this.start = new Date().getTime(); this.img.src = "http://" + ip; this.timer = setTimeout(function() { _that.bad();}, 1500); } } 

这适用于我testing过的所有types的服务器(Web服务器,FTP服务器和游戏服务器)。 它也适用于端口。 如果任何人遇到失败的用例,请发表评论,我会更新我的答案。

更新 :上一个链接已被删除。 如果有人发现或实施上述,请评论,我会将其添加到答案。

更新2 :@trante很好,提供了一个jsFiddle。

http://jsfiddle.net/GSSCD/203/

更新3 :@Jonathon创build了一个GitHub回购实现。

https://github.com/jdfreder/pingjs

更新4 :看起来这个实现不再可靠。 人们也报告说,Chrome不再支持这一切,抛出一个net::ERR_NAME_NOT_RESOLVED错误。 如果有人可以validation替代解决scheme,我会把它作为接受的答案。

你可以试试这个:

ping.html放在服务器上,不pipe有没有任何内容,在javascript上都做如下:

 <script> function ping(){ $.ajax({ url: 'ping.html', success: function(result){ alert('reply'); }, error: function(result){ alert('timeout/error'); } }); } </script> 

你不能直接在JavaScript中“ping”。 可能还有其他一些方法:

  • 阿贾克斯
  • 使用isReachable的java applet
  • 编写一个服务器端脚本,使用AJAX与您的服务器脚本进行通信
  • 你可能也可以ping通闪光(动作)

Ping是ICMP,但是如果在远程服务器上有任何打开的TCP端口,可以这样来实现:

 function ping(host, port, pong) { var started = new Date().getTime(); var http = new XMLHttpRequest(); http.open("GET", "http://" + host + ":" + port, /*async*/true); http.onreadystatechange = function() { if (http.readyState == 4) { var ended = new Date().getTime(); var milliseconds = ended - started; if (pong != null) { pong(milliseconds); } } }; try { http.send(null); } catch(exception) { // this is expected } } 

您不能在浏览器Javascript中定期ping,但是您可以通过例如从远程服务器加载图像来了解远程服务器是否处于活动状态。 如果加载失败 – >服务器closures。

你甚至可以使用onload-event来计算加载时间。 这里是一个如何使用onload事件的例子 。

要快速保持请求,请cachingping的服务器端结果,并每隔几分钟(或准确无误)更新ping文件或数据库。 你可以使用cron来运行一个shell命令,并把你的输出写入一个文件中,networking服务器将把这个文件包含到你的视图中。

标准ping的问题是ICMP, 很多地方出于安全和交通的原因不允许 。 这可能解释失败。

1.9之前的Ruby有一个基于TCP的ping.rb ,它将运行在Ruby 1.9+之上。 你所要做的就是把它从1.8.7安装拷贝到别的地方。 我只是确认它会ping我的家庭路由器。

搭配websocket解决scheme

 function ping(ip, isUp, isDown) { var ws = new WebSocket("ws://" + ip); ws.onerror = function(e){ isUp(); ws = null; }; setTimeout(function() { if(ws != null) { ws.close(); ws = null; isDown(); } },2000); } 

如果你想看到服务器是否存在,你可以使用下面的命令:

 function isValidURL(url) { var encodedURL = encodeURIComponent(url); var isValid = false; $.ajax({ url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json", type: "get", async: false, dataType: "json", success: function(data) { isValid = data.query.results != null; }, error: function(){ isValid = false; } }); return isValid; } 

这将返回是否存在服务器的真/假指示。

如果你想要反应时间,稍作修改就可以了:

 function ping(url) { var encodedURL = encodeURIComponent(url); var startDate = new Date(); var endDate = null; $.ajax({ url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22" + encodedURL + "%22&format=json", type: "get", async: false, dataType: "json", success: function(data) { if (data.query.results != null) { endDate = new Date(); } else { endDate = null; } }, error: function(){ endDate = null; } }); if (endDate == null) { throw "Not responsive..."; } return endDate.getTime() - startDate.getTime(); } 

用法是微不足道的:

 var isValid = isValidURL("http://example.com"); alert(isValid ? "Valid URL!!!" : "Damn..."); 

要么:

 var responseInMillis = ping("example.com"); alert(responseInMillis); 

这里有很多疯狂的答案,尤其是关于CORS的 –

你可以做一个HTTP HEAD请求(如GET,但没有有效载荷)。 请参阅https://ochronus.com/http-head-request-good-uses/

它不需要预检检查,这是由于规范的旧版本造成的混淆,请参阅为什么交叉源HEAD请求需要预检检查?

所以你可以使用上面的使用jQuery库(没有说),但与

 type: 'HEAD' 

—>

 <script> function ping(){ $.ajax({ url: 'ping.html', type: 'HEAD', success: function(result){ alert('reply'); }, error: function(result){ alert('timeout/error'); } }); } </script> 

当然,你也可以使用香草js或dojo或其他…

我不知道你正在运行的Ruby版本是什么,但是你是否尝试过使用Ruby来代替JavaScript? http://raa.ruby-lang.org/project/net-ping/

您可以使用下面的命令从javaScript运行DOS ping.exe命令:

 function ping(ip) { var input = ""; var WshShell = new ActiveXObject("WScript.Shell"); var oExec = WshShell.Exec("c:/windows/system32/ping.exe " + ip); while (!oExec.StdOut.AtEndOfStream) { input += oExec.StdOut.ReadLine() + "<br />"; } return input; } 

这是要求什么,或者我错过了什么?

只是取代

 file_get_contents 

 $ip = $_SERVER['xxx.xxx.xxx.xxx']; exec("ping -n 4 $ip 2>&1", $output, $retval); if ($retval != 0) { echo "no!"; } else{ echo "yes!"; } 

这可能比这一切容易得多。 如果你想加载你的页面,然后检查一些外部页面的可用性或内容来触发其他网页的活动,你可以使用只有JavaScript和PHP这样做。

yourpage.php

 <?php if (isset($_GET['urlget'])){ if ($_GET['urlget']!=''){ $foreignpage= file_get_contents('http://www.foreignpage.html'); // you could also use curl for more fancy internet queries or if http wrappers aren't active in your php.ini // parse $foreignpage for data that indicates your page should proceed echo $foreignpage; // or a portion of it as you parsed exit(); // this is very important otherwise you'll get the contents of your own page returned back to you on each call } } ?> <html> mypage html content ... <script> var stopmelater= setInterval("getforeignurl('?urlget=doesntmatter')", 2000); function getforeignurl(url){ var handle= browserspec(); handle.open('GET', url, false); handle.send(); var returnedPageContents= handle.responseText; // parse page contents for what your looking and trigger javascript events accordingly. // use handle.open('GET', url, true) to allow javascript to continue executing. must provide a callback function to accept the page contents with handle.onreadystatechange() } function browserspec(){ if (window.XMLHttpRequest){ return new XMLHttpRequest(); }else{ return new ActiveXObject("Microsoft.XMLHTTP"); } } </script> 

这应该做到这一点。

被触发的JavaScript应该包括clearInterval(stopmelater)

让我知道这是否适合你

杰瑞

你可以尝试在你的网页中使用PHP …这样的事情:

 <html><body> <form method="post" name="pingform" action="<?php echo $_SERVER['PHP_SELF']; ?>"> <h1>Host to ping:</h1> <input type="text" name="tgt_host" value='<?php echo $_POST['tgt_host']; ?>'><br> <input type="submit" name="submit" value="Submit" > </form></body> </html> <?php $tgt_host = $_POST['tgt_host']; $output = shell_exec('ping -c 10 '. $tgt_host.'); echo "<html><body style=\"background-color:#0080c0\"> <script type=\"text/javascript\" language=\"javascript\">alert(\"Ping Results: " . $output . ".\");</script> </body></html>"; ?> 

这是没有testing,所以它可能有错别字等…但我相信它会工作。 还可以改进…