C# 设置访问超时,使用 TcpClient 检查网址是否活动(被墙)

最近使用 C# HttpWebRequest 写网络模块的时候,即使设置了 Timeout,也会在

Request = (HttpWebRequest)HttpWebRequest.Create(URL);

卡住,因为上面这段代码要判断服务器是否可访问,这里的超时是 20s,也就是说,如果这个网站被墙了,就会在这里卡 20s 左右,单独设置 HttpWebRequest.TimeOut 是无效的。

Karl Glennon 在 问题 中说到

当我们检查的服务器停机时,无论我们尝试什么,我们都无法使超时小于21秒。为了解决这个问题,我们组合了TcpClient检查(查看域是否为活动的)和单独检查(查看URL是否为活动的)

解决办法是,先使用 TcpClient 判断 Url 是否活动,即

public static bool IsUrlAlive(string aUrl, int aTimeoutSeconds)
{
    try
    {
        //check the domain first
        if (IsDomainAlive(new Uri(aUrl).Host, aTimeoutSeconds))
        {
            //only now check the url itself
            var request = System.Net.WebRequest.Create(aUrl);
            request.Method = "HEAD";
            request.Timeout = aTimeoutSeconds * 1000;
            var response = (HttpWebResponse)request.GetResponse();
            return response.StatusCode == HttpStatusCode.OK;
        }
    }
    catch
    {
    }
    return false;

}

private static bool IsDomainAlive(string aDomain, int aTimeoutSeconds)
{
    try
    {
        using (TcpClient client = new TcpClient())
        {
            var result = client.BeginConnect(aDomain, 80, null, null);

            var success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(aTimeoutSeconds));

            if (!success)
            {
                return false;
            }

            // we have connected
            client.EndConnect(result);
            return true;
        }
    }
    catch
    {
    }
    return false;
}

你可能感兴趣的:(C#)