답변:
네이티브 Image객체를 매우 영리하게 사용하여 이것을 달성하는 사람을 발견했습니다 .
소스에서 이것은 주요 기능입니다 (소스의 다른 부분에 의존하지만 아이디어를 얻습니다).
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);
}
}
이것은 내가 테스트 한 모든 유형의 서버 (웹 서버, ftp 서버 및 게임 서버)에서 작동합니다. 포트와도 작동합니다. 누구든지 사용 사례가 실패하면 의견을 게시하면 답변을 업데이트하겠습니다.
업데이트 : 이전 링크가 제거되었습니다. 위의 내용을 찾거나 구현하는 사람은 의견을 말하고 답변에 추가하겠습니다.
업데이트 2 : @trante는 jsFiddle을 제공하기에 충분했습니다.
http://jsfiddle.net/GSSCD/203/
업데이트 3 : @Jonathon은 구현으로 GitHub 저장소를 만들었습니다.
https://github.com/jdfreder/pingjs
업데이트 4 :이 구현이 더 이상 신뢰할 수없는 것처럼 보입니다. 사람들은 또한 Chrome이 더 이상 모든 것을 지원하지 않아 net::ERR_NAME_NOT_RESOLVED오류가 발생 한다고보고합니다 . 누군가가 다른 해결책을 확인할 수 있다면 나는 그것을 정답으로 넣을 것입니다.
.... 그러나 onerror가 '좋은'것이기 때문에 이것은 응답했다
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
}
}
ping("example.com", "77", function(m){ console.log("It took "+m+" miliseconds."); })..... 전화 예
onreadystatechange아직 실행되지 않았습니다. 즉, 상태가 변경 될 때 픽업하려면 콜백이 필요합니다.
test.zzzzzzzzz, "77", function (m) {console.log ( ""+ m + "밀리 초가 걸렸습니다.");}) "67 밀리 초가 걸렸습니다." ping ( stackoverflow.com, "80", function (m) {console.log ( ""+ m + "밀리 초가 걸렸습니다.");}) CORS-Error : developer.mozilla.org/en-US/docs/Web/ HTTP / CORS / Errors /… 원격 컴퓨터가 온라인 상태 일 때이 코드를 어떻게 확인할 수 있는지 모르겠습니다.
당신은 이것을 시도 할 수 있습니다 :
내용이 있거나없는 서버 에 ping.html 을 넣고 자바 스크립트에서 다음과 같이하십시오.
<script>
function ping(){
$.ajax({
url: 'ping.html',
success: function(result){
alert('reply');
},
error: function(result){
alert('timeout/error');
}
});
}
</script>
자바 스크립트에서는 직접 "핑"할 수 없습니다. 몇 가지 다른 방법이있을 수 있습니다.
브라우저 Javascript에서 정기적으로 핑을 수행 할 수는 없지만 원격 서버에서 이미지를로드하는 등의 방법으로 원격 서버가 활성 상태인지 확인할 수 있습니다. 로딩이 실패하면-> 서버 다운.
onload-event를 사용하여 로딩 시간을 계산할 수도 있습니다. 다음은 onload 이벤트를 사용하는 방법 의 예 입니다.
ping명령 을 활용할 수 있습니다 . 산업의 힘입니다. 또는 다양한 유형의 하트 비트 검사를 사용하여 호스트가 실행 중인지 모니터링 할 수있는 모든 종류의 무료 / 오픈 소스 앱이 있습니다.
웹 소켓 솔루션을 사용하여 피칭 ...
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);
}
isUp();호출이 onopen이벤트 핸들러 에 있어야합니까 ? :)
isUp();하는 콜백. 또는 비 websocket-y 포트를 명확하게 추가하여 완화하십시오.
요청을 빠르게 유지하려면 핑의 서버 측 결과를 캐시하고 2 분마다 (또는 원하는대로) 핑 파일 또는 데이터베이스를 업데이트하십시오. cron을 사용하여 8 핑으로 쉘 명령을 실행하고 출력을 파일에 쓸 수 있습니다. 웹 서버는이 파일을보기에 포함시킵니다.
보고자하는 것이 서버가 "존재"하는지 여부 인 경우 다음을 사용할 수 있습니다.
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);
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin과 성공 콜백이 호출되지 않습니다
표준 핑의 문제점은 ICMP이므로 보안 및 트래픽상의 이유로 많은 장소를 통과하지 못합니다. . 실패를 설명 할 수 있습니다.
1.9 이전의 Ruby에는 TCP 기반이 있으며 Ruby 1.9 이상에서 ping.rb실행됩니다. 1.8.7 설치에서 다른 곳으로 복사하기 만하면됩니다. 방금 홈 라우터를 ping하여 작동한다는 것을 확인했습니다.
여기 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 버전을 모르지만 javascript 대신 ruby에 대해 ping을 구현하려고 시도 했습니까? http://raa.ruby-lang.org/project/net-ping/
ping server.com구문을 사용하도록 변경했습니다 .
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)
});;
노드로 이것을 실행하면 Google이 다운되지 않는 한 콘솔 로그 200이됩니다.
const ping = (url, timeout = 6000) => {
return new Promise((reslove, reject) => {
const urlRule = new RegExp('(https?|ftp|file)://[-A-Za-z0-9+&@#/%?=~_|!:,.;]+[-A-Za-z0-9+&@#/%=~_|]');
if (!urlRule.test(url)) reject('invalid url');
try {
fetch(url)
.then(() => reslove(true))
.catch(() => reslove(false));
setTimeout(() => {
reslove(false);
}, timeout);
} catch (e) {
reject(e);
}
});
};
이처럼 사용하십시오 :
ping('https://stackoverflow.com/')
.then(res=>console.log(res))
.catch(e=>console.log(e))
다음을 사용하여 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;
}
이것이 요청 된 것입니까, 아니면 뭔가 빠졌습니까?
모든 것보다 훨씬 쉬울 수 있습니다. 페이지를로드하고 다른 웹 페이지 활동을 트리거하기 위해 일부 외국 페이지의 가용성 또는 내용을 확인하려면 이와 같은 자바 스크립트 및 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>
그렇게해야합니다.
트리거 된 자바 스크립트에는 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>";
?>
이것은 테스트되지 않았으므로 오타 등이있을 수 있지만 작동 할 것이라고 확신합니다. 너무 향상 될 수 ...
"/?cachebreaker="+new Date().getTime();필요한 경우 img src의 끝에 a 를 추가하면 피할 수 있습니다 .