C# 服务器连接监控

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.NetworkInformation;
using System.Net.Security;
using System.Security.Cryptography.X509Certificates;
using System.Text;

namespace SYS_TEST.OtherClass
{
    //服务器连接监控
    public class ServiceMonitor
    {
        private string strMsg = "";

        /// 
        /// 网站连接(IP连接/网址连接)
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool TryConnectToServer(string address, int port, string type, int timeout)
        {
            try
            {
                if (type == "IP")
                {
                    Ping pingsend = new Ping();
                    PingReply pingreply = pingsend.Send(address, timeout);
                    if (pingreply.Status != IPStatus.Success)
                    {
                        strMsg = "响应状态为:" + pingreply.Status.ToString();
                        return false;
                    }
                }
                if (type == "HTTP")
                {
                    ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(CheckValidationResult);//验证服务器证书回调自动验证
                    WebRequest myRequest = WebRequest.Create(address);
                    myRequest.Timeout = timeout;
                    WebResponse myResponse = myRequest.GetResponse();
                    myResponse.Close();
                }
            }
            catch (Exception e)
            {
                strMsg = "连接服务器异常,原因:" + e.Message;
                return false;
            }
            return true;
        }
        /// 
        /// FTP连接
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        public bool TryConnectToFtp(string address, int port, int timeout, string ftpUserName, string ftpUserPwd)
        {
            try
            {
                FtpWebRequest ftprequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(address));
                ftprequest.Credentials = new NetworkCredential(ftpUserName, ftpUserPwd);
                ftprequest.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
                ftprequest.Timeout = timeout;
                FtpWebResponse ftpResponse = (FtpWebResponse)ftprequest.GetResponse();
                ftpResponse.Close();
            }
            catch (Exception e)
            {
                strMsg = "连接服务器异常,原因:" + e.Message;
                return false;
            }
            return true;
        }
        /// 
        /// 忽略网站证书校验
        /// 
        /// 
        /// 
        /// 
        /// 
        /// 
        protected bool CheckValidationResult(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors errors)
        {   // 总是接受  
            return true;
        }
    }
}

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