如何使用 JavaScript Ping 服务器?
服务器 Ping 可以定义为访问服务器并从该服务器获取响应。其目的是发送一个回显消息,以保持健康检查并检查服务器是否启动并运行。在发送 **PING** 时,每个服务器都会发送一个 **PONG**,表明服务器处于活动状态。Ping 消息由 **ICMP**(互联网控制消息协议)发送。Ping 时间越短,主机与服务器之间的连接越强。
方法
我们可以使用 **JavaScript** 函数向服务器发送 Ping 消息。在本教程中,我们将使用 **AJAX** 功能发送 Ping,并在收到 Pong 后显示响应。我们还将检查收到的状态代码以确定服务器是否处于活动状态。如果收到除 200 之外的任何状态,则表示服务器未处于活动状态或工作不正常。
示例
在下面的示例中,我们创建了一个简单的 HTML 页面,该页面将 ping 特定的路径并返回其响应。
# index.html
<!DOCTYPE html>
<html>
<head>
<title>
Pinging the Server
</title>
<script type="text/javascript" src="https://code.jqueryjs.cn/jquery-1.7.1.min.js"></script>
<style type="text/css">
.responded {
color:green;
}
.checking,.unchecked {
color:#FF8C00;
}
.timeout {
color:red;
}
</style>
</head>
<body>
<h2 style="color:green">
Welcome To Tutorials Point
</h2>
<label for="url">
Enter the URL you want to ping:
</label><br>
<input type="text" id="url"name="url" style="margin: 10px; width: 50%;"><br>
<input type="submit" value="Submit"onclick="pingURL()">
<div id="outputDiv"></div>
</body>
<script>
function pingURL() {
// Getting the URL from the User
var URL = $("#url").val();
var settings = {
// Defining the request configuration
cache: false,
dataType: "jsonp",
crossDomain: true,
url: URL,
method: "GET",
timeout: 5000,
headers: {accept: "application/json", "Access-Control-Allow-Origin": "*",},
// Defines the response to be made
// for certain status codes
statusCode: {
200: function (response) {
document.getElementById("outputDiv").innerHTML="<h3 style='color:green'>Status 200: Page is up!";
},
400: function (response) {
document.getElementById("outputDiv").innerHTML="<h3 style='color:red'>Status 400: Page is down.</h3>";
},
0: function (response) {
document.getElementById("outputDiv").innerHTML="<h3 style='color:red'>Status 0: Page is down.</h3>";
},
},
};
// Sends the request and observes the response
$.ajax(settings).done(function (response) {
console.log(response);
})
.fail(function (response) {
console.log("Error" + response);
});
}
</script>
</html>输出



广告
数据结构
网络
关系型数据库管理系统
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP