简体   繁体   English

使用Javascript通过最快的ping时间对服务器列表进行排序

[英]Sort a list of servers by fastest ping time with Javascript

In my Electron app I have a list of server addresses that I need to sort by shortest response time. 在我的Electron应用程序中,我有一个服务器地址列表,我需要按照最短的响应时间对其进行排序。 I have a function that needs the sorted list: 我有一个需要排序列表的函数:

function start() {
    // first step, get list of servers
    var servers_sorted = get_sorted_list_of_servers();

    // rest of function
}

Then I have a function that iterates through the list of servers: 然后,我有一个遍历服务器列表的函数:

function get_sorted_list_of_servers() {
    // access unsorted list from file

    unsorted_servers.forEach((server) => {
        // Get ping times for each server
        // Here is where I am stuck
    });

    // Sort based on ping times....

    return sorted_list_of_servers;
}

The problem is that I'm not sure how to get the ping time for each server. 问题是我不确定如何获取每个服务器的ping时间。 I've found a couple of libraries that wrap the ping utility ( net-ping and ping ). 我发现了几个包装ping实用程序的库( net-pingping )。 However, they use callbacks (which makes sense given that pinging a server can take a minute) and I need some way of getting a list of the server times. 但是,它们使用回调(考虑到对服务器执行ping操作可能需要一分钟,因此这很有意义),我需要某种方式来获取服务器时间列表。

// From ping example code
unsorted_servers.forEach(function (server) {
    ping.promise.probe(host).then(function (res) {
        console.log(res);
        // Update a global variable here??
    });
});

I've thought about letting the callbacks update a global list but then I need some way of signalling once all the servers have been tested. 我曾考虑过让回调更新全局列表,但是一旦所有服务器都经过测试,我就需要发出某种信号。

Any guidance is appreciated. 任何指导表示赞赏。 Thanks! 谢谢!

You can use Promise.all and map to loop over your server list and wait for all of the Promises to resolve. 您可以使用Promise.allmap以遍历服务器列表,并等待所有Promises解决。 Here's a quick example using ping: 这是使用ping的简单示例:

 const sortBy = require('lodash.sortby'); const ping = require('ping'); const servers = ['google.com', 'facebook.com', 'amazon.com', 'apple.com']; Promise.all(servers.map(server => ping.promise.probe(server))).then(response => { console.log(sortBy(response, 'time')) }); 

Here's an React demo using Promise.all and rendering the results: 这是一个使用Promise.all并呈现结果的React演示:

https://server-ping-fuupenayzp.now.sh/ https://server-ping-fuupenayzp.now.sh/

and the source 和来源

https://zeit.co/rusty-dev/server-ping/fuupenayzp/source?f=src/App.js https://zeit.co/rusty-dev/server-ping/fuupenayzp/source?f=src/App.js

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM