使用C#ping服务器

idi*_*ish 0 c# networking network-programming

我试图使用Ping类ping服务器,但是在10次之后该方法返回true,我一直得到假(这意味着服务器已关闭[?]而它不是)以下是方法:

     public bool IsConnectedToInternet()
    {
            Ping p = new Ping();
            try
            {

                PingReply reply = p.Send("www.uic.co.il", 1000);
                if (reply.Status == IPStatus.Success)
                    return true;
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message.ToString());    
            }
            return false;
    }

    private void start_Click(object sender, EventArgs e)
    {
        for (; ; )
        {
            Console.WriteLine(IsConnectedToInternet);


        }
    }
Run Code Online (Sandbox Code Playgroud)

为什么我会在一段时间后变得虚假?谢谢.

Chr*_*isF 10

你在请求中充斥着服务器:

for (; ; )
{
    Console.WriteLine(IsConnectedToInternet);
}
Run Code Online (Sandbox Code Playgroud)

将在请求后尽可能快地循环发送请求.

如果您只是编写保持活动服务或服务状态控制,那么使用每分钟甚至每10分钟ping一次的计时器应该足够好了.

另外,正如其他人在他们的评论中指出的那样,你通过在getter中执行ping来滥用属性,因为调用可能需要一些时间并且属性getter应该真正返回,如果不是立即那么快.一种CheckConnection()方法会有更清晰的意图.