【问题标题】:How would I check to see if website a is online我将如何检查网站 a 是否在线
【发布时间】:2016-01-02 23:24:38
【问题描述】:

所以,我知道可以在 C# 中使用 Ping.Send(string) 来 ping 一个服务器,但是否可以 ping 特定的 Web 应用程序,而不是整个服务器。例如,有一个服务器上托管了三个网站(a、b 和 c)。服务器 IP 为 1.1.1.1。每个网站都有不同的端口。如何检查网站 a 当前是否正在托管?

【问题讨论】:

  • How to check remote IP and Port is available 的可能重复项。第二种方法可能就是你想要的。
  • 非常精确地定义“在线”,然后测试它是否符合该定义。例如,如果你决定“在线”意味着你可以获取着陆页,那么尝试获取着陆页,看看你是否成功。
  • @Coral 可用是什么意思?

标签: c# networking


【解决方案1】:

只需向网站发出请求

private bool PingWebSite(string url)
{
    try
    {
        WebRequest.Create(url).GetResponse();
        return true;
    }
    catch
    {
        return false;
    }
}

然后使用它

var isWebSiteWorking = PingWebSite("http://stackoverflow.com");

【讨论】:

    【解决方案2】:

    我不会执行 GetResponse(),因为如果该特定 Url 返回您一个 1+ GB 的文件,这将阻止您的应用程序。只需发出头部请求就足够了,或者使用 TcpClient。

    async Task<Boolean> IsAvailable()
    {
        string url = "http://www.google.com";
        try
        {
            using (var client = new HttpClient())
            {
                HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Head, url);
                var response = await client.SendAsync(request);
                if (response.IsSuccessStatusCode)
                {
                    response.Dump();
                    return true;
                }
                else
                {
                    return false;
                }
            }
        }
        catch (Exception ex)
        {
          return false;
        }
    }
    

    【讨论】:

    • 我最终使用了 TcpClient,因为它最适合我尝试做的事情。
    猜你喜欢
    • 2015-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-05-15
    • 2014-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多