zoukankan      html  css  js  c++  java
  • .NET Socket Connect 各种 超时控制扩展

    using System; 
    using System.Net; 
    using System.Net.Sockets; 
    public static class SocketExtensions 
    { 
    	/// <summary> 
    	/// Connects the specified socket. 
    	/// </summary> 
    	/// <param name="socket">The socket.</param> 
    	/// <param name="endpoint">The IP endpoint.</param> 
    	/// <param name="timeout">The timeout.</param> 
    	public static void Connect(this Socket socket, EndPoint endpoint, TimeSpan timeout) 
    	{ 
    		var result = socket.BeginConnect(endpoint, null, null); 
    		bool success = result.AsyncWaitHandle.WaitOne(timeout, true); 
    		if (success) 
    		{ socket.EndConnect(result); } 
    		else 
    		{
    			socket.Close(); throw new SocketException(10060); 
    			// Connection timed out. 
    		} 
    	} 
    
    	/// <summary> 
    	/// Connects the specified socket. 
    	/// </summary> 
    	/// <param name="socket">The socket.</param> 
    	/// <param name="host">The host.</param> 
    	/// <param name="port">The port.</param> 
    	/// <param name="timeout">The timeout.</param> 
    	public static void Connect(this Socket socket, string host, int port, TimeSpan timeout) 
    	{ 
    		AsyncConnect(socket, (s, a, o) => s.BeginConnect(host, port, a, o), timeout); 
    	}
    
    	/// <summary> 
    	/// Connects the specified socket. 
    	/// </summary> 
    	/// <param name="socket">The socket.</param> 
    	/// <param name="addresses">The addresses.</param> 
    	/// <param name="port">The port.</param> 
    	/// <param name="timeout">The timeout.</param> 
    	public static void Connect(this Socket socket, IPAddress[] addresses, int port, TimeSpan timeout) 
    	{
    		AsyncConnect(socket, (s, a, o) => s.BeginConnect(addresses, port, a, o), timeout); 
    	} 
    
    	/// <summary> 
    	/// Asyncs the connect. 
    	/// </summary> 
    	/// <param name="socket">The socket.</param> 
    	/// <param name="connect">The connect.</param> 
    	/// <param name="timeout">The timeout.</param> 
    	private static void AsyncConnect(Socket socket, Func<Socket, AsyncCallback, object, IAsyncResult> connect, TimeSpan timeout) 
    	{ 
    		var asyncResult = connect(socket, null, null); 
    		if (!asyncResult.AsyncWaitHandle.WaitOne(timeout)) 
    		{ 
    			try { socket.EndConnect(asyncResult); } 
    			catch (SocketException) { } 
    			catch (ObjectDisposedException) { } 
    		} 
    	} 
    }
    

    TcpClient Connect 超时控制  

    using (TcpClient tcp = new TcpClient())  
    {  
        IAsyncResult ar = tcp.BeginConnect("127.0.0.1", 80, null, null);  
        System.Threading.WaitHandle wh = ar.AsyncWaitHandle;  
        try 
        {  
           if (!ar.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(5), false))  
           {  
               tcp.Close();  
               throw new TimeoutException();  
           }  
            tcp.EndConnect(ar);  
        }  
        finally 
        {  
            wh.Close();  
        }  
    } 
    

    Ping 超时 控制

    public static bool TryPing(string strIpAddress, int intPort, int nTimeoutMsec) 
    { 
        Socket socket = null; 
        try 
        { 
            socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            socket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.DontLinger, false); 
    
    
            IAsyncResult result = socket.BeginConnect(strIpAddress, intPort, null, null); 
            bool success = result.AsyncWaitHandle.WaitOne(nTimeoutMsec, true); 
    
            return socket.Connected; 
        } 
        catch 
        { 
            return false; 
        } 
        finally 
        { 
            if (null != socket) 
                socket.Close(); 
        } 
    } 
    

    连接测试 超时控制

    public static bool TestConnection(string ipAddress, int Port, TimeSpan waitTimeSpan) 
    { 
        using (TcpClient tcpClient = new TcpClient()) 
        { 
            IAsyncResult result = tcpClient.BeginConnect(ipAddress, Port, null, null); 
            WaitHandle timeoutHandler = result.AsyncWaitHandle; 
            try 
            { 
                if (!result.AsyncWaitHandle.WaitOne(waitTimeSpan, false)) 
                { 
                    tcpClient.Close(); 
                    return false; 
                } 
    
                tcpClient.EndConnect(result); 
            } 
            catch (Exception ex) 
            { 
                return false; 
            } 
            finally 
            { 
                timeoutHandler.Close(); 
            } 
            return true; 
        } 
    } 
    

      

      

  • 相关阅读:
    程序员转型架构师,推荐你读这几本书
    Dubbo服务发现源码解析
    高可用架构之限流降级
    为什么Kafka速度那么快
    从分布式一致性到共识机制(三)拜占庭问题
    从分布式一致性到共识机制(二)Raft算法
    三分钟看完京东区块链白皮书
    轻松理解零知识证明
    三大去中心化交易协议对比
    从分布式一致性到共识机制(一)Paxos算法
  • 原文地址:https://www.cnblogs.com/binsys/p/2711198.html
Copyright © 2011-2022 走看看