C#检查Windows服务器是否联机

本文关键字:是否 联机 服务器 Windows 检查 | 更新日期: 2023-09-27 18:07:53

可能重复:
检查服务器是否可用

我正在用C#编写一个程序,一个接一个地查询我们域上的Windows服务器。目前,如果服务器脱机或出现故障,程序将挂起等待答复,最好的等待方式是什么?如果没有收到响应,请转到下一台服务器?我以前从来没有这样做过,所以我们非常感谢您的帮助。

谢谢Steve

C#检查Windows服务器是否联机

听起来好像你想看看BackgroundWorker和线程(Thread类(。我想你会通过调用任何可能的调用来检查你的服务器来阻塞UI线程。

通过使用线程,您可以向用户报告到底发生了什么,并在需要时应用自己的超时。

您可以使用C#中的PingReplay类ping服务器:

using System;
using System.Net;
using System.Net.NetworkInformation;
using System.Text;
namespace PingTest
{
    public class PingExample
    {
        // args[0] can be an IPaddress or host name.
        public static void Main (string[] args)
        {
            Ping pingSender = new Ping();
            PingOptions options = new PingOptions();
            options.DontFragment = true;
            // Create a buffer of 32 bytes of data to be transmitted.
            string data = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
            byte[] buffer = Encoding.ASCII.GetBytes (data);
            int timeout = 120;
            PingReply reply = pingSender.Send (args[0], timeout, buffer, options);
            if (reply.Status == IPStatus.Success)
            {
                Console.WriteLine ("Address: {0}", reply.Address.ToString ());
                Console.WriteLine ("RoundTrip time: {0}", reply.RoundtripTime);
                Console.WriteLine ("Time to live: {0}", reply.Options.Ttl);
                Console.WriteLine ("Don't fragment: {0}", reply.Options.DontFragment);
                Console.WriteLine ("Buffer size: {0}", reply.Buffer.Length);
            }
        }
    }
}

该代码已从MSDN中采用,请参阅此处。