是否可以从Javascript ping服务器?
我正在制作一个需要检查远程服务器是否在线的web应用程序。当我从命令行运行它时,我的页面负载将上升到整整60秒(对于8个条目,它将随着更多条目线性扩展) 我决定在用户端执行ping操作。这样,我可以加载页面,让他们在浏览我的内容时等待“服务器在线”数据是否可以从Javascript ping服务器?,javascript,Javascript,我正在制作一个需要检查远程服务器是否在线的web应用程序。当我从命令行运行它时,我的页面负载将上升到整整60秒(对于8个条目,它将随着更多条目线性扩展) 我决定在用户端执行ping操作。这样,我可以加载页面,让他们在浏览我的内容时等待“服务器在线”数据 如果有人能回答上述问题,或者他们知道快速加载我的页面的解决方案,我会非常感激。您不能在浏览器Javascript中进行常规ping,但您可以通过从远程服务器加载图像等方法来确定远程服务器是否处于活动状态。如果加载失败->服务器关闭 您甚至可以使用
如果有人能回答上述问题,或者他们知道快速加载我的页面的解决方案,我会非常感激。您不能在浏览器Javascript中进行常规ping,但您可以通过从远程服务器加载图像等方法来确定远程服务器是否处于活动状态。如果加载失败->服务器关闭 您甚至可以使用onload事件来计算加载时间。下面是一个如何使用onload事件。您不能在javascript中直接“ping”。 可能还有其他几种方法:
- 阿贾克斯
- 使用带有
- 编写用于ping的服务器端脚本,并使用AJAX与服务器端脚本通信
- 您还可以在flash中ping(actionscript)
- 我不知道您运行的是哪个版本的Ruby,但您是否尝试过为Ruby而不是javascript实现ping 您可以尝试以下方法:
将ping.html放在有或无任何内容的服务器上,在javascript上执行以下操作:
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
函数ping(){
$.ajax({
url:'ping.html',
成功:功能(结果){
警惕(“回复”);
},
错误:函数(结果){
警报(“超时/错误”);
}
});
}
您可以尝试在您的网页中使用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>";
?>
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
}
}
为了使请求保持快速,请缓存ping的服务器端结果,并每隔几分钟更新ping文件或数据库(或以您希望的精度为准)。您可以使用cron对8次ping运行shell命令,并将输出写入文件,Web服务器会将此文件包含到您的视图中。标准ping的问题是它们是ICMP,而ICMP是。这或许可以解释失败的原因
Ruby 1.9之前的版本有一个基于TCP的ping.rb
,它将与Ruby 1.9+一起运行。您所要做的就是将它从1.8.7安装复制到其他地方。我刚刚确认它将通过ping我的家庭路由器来运行。这可能比这容易得多。如果您希望加载页面,然后检查某个外部页面的可用性或内容以触发其他网页活动,您可以仅使用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>
mypage html内容
...
var stopmelater=setInterval(“getforeignurl('?urlget=doesntmatter')”,2000年);
函数getforeignurl(url){
var handle=browserspec();
handle.open('GET',url,false);
handle.send();
var returnedPageContents=handle.responseText;
//分析页面内容以了解您的外观,并相应地触发javascript事件。
//使用handle.open('GET',url,true)允许javascript继续执行。必须提供回调函数以接受带有handle.onreadystatechange()的页面内容
}
函数browserspec(){
if(window.XMLHttpRequest){
返回新的XMLHttpRequest();
}否则{
返回新的ActiveXObject(“Microsoft.XMLHTTP”);
}
}
应该这样做
触发的javascript应该包括clearInterval(stopmelater)
如果对你有效,请告诉我
杰瑞只要换掉
file_get_contents
与
我发现有人非常巧妙地使用本机Image
对象来实现这一点
从它们的源代码来看,这是主要功能(它依赖于源代码的其他部分,但您可以理解)
这适用于我测试过的所有类型的服务器(web服务器、ftp服务器和游戏服务器)。它也适用于端口。如果任何人遇到失败的用例,请在评论中发表,我将更新我的答案
更新:上一个链接已被删除。如果有人发现或实现了上述内容,请发表评论,我会将其添加到答案中
更新2:@trante很好地提供了一个JSFIDLE
更新3:@Jonathon用实现创建了一个GitHub repo
更新4:看起来此实现不再可靠。人们还报告说Chrome不再支持这一切,抛出了一个net::ERR\u NAME\u NOT\u RESOLVED
错误。如果有人可以验证替代解决方案,我会将其作为可接受的答案。Ping是ICMP,但如果远程服务器上有任何打开的TCP端口,则可以这样实现:
<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>";
?>
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
}
}
使用websocket解决方案加入
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);
}
您可以使用以下命令从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;
}
功能ping(ip)
{
var输入=”;
var WshShell=newActiveXObject(“WScript.Shell”);
var oExec=WshShell.Exec(“c:/windows/system32/ping.exe”+ip);
而(!oExec.StdOut.AtEndOfStream)
{
输入+=oExec.StdOut.ReadLine()+“
”;
}
返回输入;
}
这是要求的,还是我遗漏了什么?如果您试图查看服务器是否“存在”,您可以使用以下命令:
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...");
或:
这里有很多疯狂的答案,尤其是关于CORS-
您可以执行http头请求(如GET,但没有有效负载)。
看
它不需要飞行前检查,混淆是因为规范的旧版本,请参阅
因此,您可以使用上面的答案,即使用jQuery库(没有说),但是
type: 'HEAD'
--->
乐趣
type: 'HEAD'
<script>
function ping(){
$.ajax({
url: 'ping.html',
type: 'HEAD',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
let webSite = 'https://google.com/'
https.get(webSite, function (res) {
// If you get here, you have a response.
// If you want, you can check the status code here to verify that it's `200` or some other `2xx`.
console.log(webSite + ' ' + res.statusCode)
}).on('error', function(e) {
// Here, an error occurred. Check `e` for the error.
console.log(e.code)
});;