我有以下代码正在运行并 ping 所有 Runescape 游戏服务器,并在控制台中返回 IP 地址列表和相应的“往返”时间。
编辑“忽略一些旧评论”
我遇到以下问题:
A) 如何返回所有服务器中最低的 ping 并将其写入控制台?
B)如何跨方法返回当前“server.ToString()”的原始主机名或“编号”?
public void buttonClick_Click(object sender, EventArgs e)
{
Console.WriteLine();
Ping();
}
public static void Ping()
{
for (int server = 1; server <= 110; server++)
{
string hostname = "oldschool" + server.ToString() + ".runescape.com";
// Get an object that will block the main thread.
AutoResetEvent waiter = new AutoResetEvent(false);
// Ping's the local machine.
Ping pingSender = new Ping();
// When the PingCompleted event is raised,
// the PingCompletedCallback method is called.
pingSender.PingCompleted += new PingCompletedEventHandler(PingCompletedCallback);
// Create a buffer of 32 bytes of data to be transmitted.
string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
byte[] buffer = Encoding.ASCII.GetBytes(data);
//Console.WriteLine("Send Before Async.");
// Send the ping asynchronously.
// Use the waiter as the user token.
// When the callback completes, it can wake up this thread.
pingSender.SendAsync(hostname, 1000, waiter);
//Console.WriteLine("Ping example completed.");
}
}
private static void PingCompletedCallback(object sender, PingCompletedEventArgs e)
{
// If the operation was canceled, display a message to the user.
if (e.Cancelled)
{
Console.WriteLine("Ping canceled.");
// Let the main thread resume.
// UserToken is the AutoResetEvent object that the main thread
// is waiting for.
((AutoResetEvent)e.UserState).Set();
}
// If an error occurred, display the exception to the user.
if (e.Error != null)
{
Console.WriteLine("Ping failed:");
Console.WriteLine(e.Error.ToString());
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
PingReply reply = e.Reply;
DisplayReply(reply);
// Let the main thread resume.
((AutoResetEvent)e.UserState).Set();
}
public static void DisplayReply(PingReply reply)
{
List<long> lag = new List<long>();
if (reply == null)
return;
Console.WriteLine("Status: {0}", reply.Status);
if (reply.Status == IPStatus.Success)
{
Console.WriteLine("\r\n");
Console.WriteLine("Address: {0}", reply.Address);
Console.WriteLine("Ping: {0}", reply.RoundtripTime);
}
return;
}