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; 
        } 
    } 
    

      

      

  • 相关阅读:
    后台管理UI的选择
    通过Js对电话和姓名身份证等进行部分隐藏处理
    12个用得着的JQuery代码片段
    Java获取登录用户IP地址
    Android Gson解析json详解
    Android——SD卡工具类——SDCardUtils.java
    【读书笔记】---《失控》
    【读书笔记】.Net并行编程(三)---并行集合
    Wix 安装部署教程(十六) -- 自动生成多语言文件
    【月末轻松篇】--- 那些奇葩的Bugs
  • 原文地址:https://www.cnblogs.com/binsys/p/2711198.html
Copyright © 2011-2022 走看看