[英]C# Check Remote Server
如果有远程服务器,有人可以建议检查(使用.NET 3.5)的最佳方法吗?
我正在考虑使用以下代码,但想知道如果社区有另一种选择,是否存在更好的方法。
TcpClient client = new TcpClient("MyServer", 80);
if (!client.Connected)
{
throw new Exception("Unable to connect to MyServer on Port 80");
}
client.Close();
如果您只是想查看给定服务器是否在线,那么在大多数情况下,简单的ping应该可以完成工作。
PingReply pingReply;
using (var ping = new Ping())
pingReply = ping.Send("http://www.stackoverflow.com/");
var available = pingReply.Status == IPStatus.Success;
使用此方法,您也不会以任何方式滥用HTTP服务器。
否则(如果你想检查特定端口上是否可以连接),那基本上看起来很好。
只是为了添加丹的答案......我只需要实现这个,这里有一个很好的小代码片段,可以帮助那些从谷歌这里制作它的人。
Imports System.Net
Private Function URLExists(pURL As String) As Boolean
Try
'Creating the HttpWebRequest
Dim request As HttpWebRequest = TryCast(WebRequest.Create(pURL), HttpWebRequest)
'Setting the Request method HEAD, you can also use GET too.
request.Method = "HEAD"
'Getting the Web Response.
Dim response As HttpWebResponse = TryCast(request.GetResponse(), HttpWebResponse)
'Returns TURE if the Status code == 200
Return (response.StatusCode = HttpStatusCode.OK)
Catch
'Any exception will returns false.
Return False
End Try
End Function
抱歉这是VB,但这就是我面前的情况。 我将把它作为练习让读者根据需要将其转换为C#。
如果您使用的是以前版本的.NET Framework,就像我一样,版本2,您将没有Ping,也没有System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable()
。 然后,您可以使用HttpWebRequest
检查主机的异常:
public static bool AccessToWebService()
{
string host = "http://192.168.99.41";
try
{
HttpWebRequest request = (HttpWebRequest) WebRequest.Create(host);
request.Method = "HEAD";
HttpWebResponse response = (HttpWebResponse) request.GetResponse();
return response.StatusCode == HttpStatusCode.OK;
}
catch (Exception)
{
return false;
}
}
我猜你想检查一下网站是否可用。 您可以使用System.Net.WebRequest
并检查结果。
更新:根据您的评论,如果您有一些服务器(和服务)要监控,那么使用Nagios , HostMonitor或IPSentry等软件包可能更好,而不是自己滚动。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.