前端有什么包/库可以做到ping的时候获取ping的一条一条地数据?

前端有什么包/库可以做到ping的时候获取如下的一条一条地数据?

% ping baidu.com
PING baidu.com (39.156.66.10): 56 data bytes
64 bytes from 39.156.66.10: icmp_seq=0 ttl=47 time=44.301 ms
64 bytes from 39.156.66.10: icmp_seq=1 ttl=47 time=43.313 ms
64 bytes from 39.156.66.10: icmp_seq=2 ttl=47 time=42.916 ms
64 bytes from 39.156.66.10: icmp_seq=3 ttl=47 time=43.272 ms
64 bytes from 39.156.66.10: icmp_seq=4 ttl=47 time=49.445 ms
64 bytes from 39.156.66.10: icmp_seq=5 ttl=47 time=50.274 ms
64 bytes from 39.156.66.10: icmp_seq=6 ttl=47 time=43.728 ms
64 bytes from 39.156.66.10: icmp_seq=7 ttl=47 time=43.077 ms
64 bytes from 39.156.66.10: icmp_seq=8 ttl=47 time=43.127 ms
64 bytes from 39.156.66.10: icmp_seq=9 ttl=47 time=43.001 ms
^C
--- baidu.com ping statistics ---
10 packets transmitted, 10 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 42.916/44.645/50.274/2.642 ms

我经过寻找,有npm i ping 这样的包,但是不能获取如上的一条一条地数据,

var ping = require('ping');

var hosts = ['192.168.1.1', 'google.com', 'yahoo.com'];
hosts.forEach(function(host){
    ping.sys.probe(host, function(isAlive){
        var msg = isAlive ? 'host ' + host + ' is alive' : 'host ' + host + ' is dead';
        console.log(msg);
    });
});

直接获取到结果:

host yahoo.com is alive
host google.com is alive
host 192.168.1.1 is dead

但是没有我上面截图的效果,我想要直接进ping进而得到每个发出的ping包的返回结果。请问是否有这样的库呢?

阅读 2.5k
2 个回答

你要在命令行下执行的话,直接用 child_process 的 spawn 就可以了呀

const { spawn } = require('child_process')
const command = 'ping baidu.com'

const spawnObj = spawn('cmd', [`/C chcp 65001>nul && ${command}`])
spawnObj.stdout.on('data', function (data) {
  console.log(data.toString())
})
spawnObj.stderr.on('data', (data) => {
  console.log(data)
})

服务器:

const express = require('express');
const http = require('http');
const WebSocket = require('ws');
const ping = require('ping');

const app = express();
const server = http.createServer(app);
const wss = new WebSocket.Server({ server });

wss.on('connection', (ws) => {
    ws.on('message', (message) => {
        if (message === 'ping') {
            let hosts = ['baidu.com'];
            hosts.forEach((host) => {
                ping.promise.probe(host, { min_reply: 10 }).then((res) => {
                    res.output.forEach((line) => {
                        ws.send(line);
                    });
                });
            });
        }
    });
});

server.listen(8080);

前端

const ws = new WebSocket('ws://your-server-address:8080');

ws.onopen = () => {
    ws.send('ping');
};

ws.onmessage = (event) => {
    console.log(event.data);
};
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题