要创建一个在线Ping检测的网页,您可以使用HTML、CSS和JavaScript来实现。以下是一个简单的示例,其中使用了Node.js的`ping`库来实现Ping的功能。在前端,我们创建一个简单的表单,用户可以输入想要Ping的地址,并在点击按钮后显示结果。
1. 创建Node.js后端
首先,您需要设置一个Node.js环境并安装`ping`库。
bash
mkdir ping-detection
cd ping-detection
npm init -y
npm install express ping cors
然后,创建一个`server.js`文件,并添加以下代码:
javascript
const express = require('express');
const ping = require('ping');
const cors = require('cors');
const app = express();
const port = 3000;
app.use(cors());
app.use(express.json());
app.post('/ping', async (req, res) => {
const { host } = req.body;
try {
const result = await ping.promise.probe(host);
res.json(result);
} catch (error) {
res.status(500).json({ error: 'Error pinging host' });
}
});
app.listen(port, () => {
console.log(`Server running at http://localhost:${port}`);
});
2. 创建前端HTML文件
然后,在同一目录下创建一个`index.html`文件,并添加以下代码:
html
body { font-family: Arial, sans-serif; margin: 20px; }
input[type="text"] { width: 300px; }
button { margin-left: 10px; }
#result { margin-top: 20px; }
async function pingHost() {
const host = document.getElementById('host').value;
const response = await fetch('http://localhost:3000/ping', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ host })
});
const result = await response.json();
displayResult(result);
}
function displayResult(result) {
const resultDiv = document.getElementById('result');
resultDiv.innerHTML = `
Alive: ${result.alive}
Time: ${result.time ? result.time + ' ms' : 'N/A'}
`;
}
3. 运行服务
在命令行中运行Node.js服务器:
bash
node server.js
然后,您可以打开`index.html`文件,在浏览器中使用这个在线Ping检测工具。只需输入要Ping的主机地址,然后点击"Ping"按钮,即可查看结果。
注意事项
- 请确保您的Node.js服务器可以接受来自客户端的请求。
- 在生产环境中,您可能还需要考虑安全性和异常处理。
- 在某些情况下,某些网络安全设置可能会阻止Ping请求。
查看详情
查看详情