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

  

  

posted @ 2012-10-04 01:17  BinSys  阅读(1818)  评论(0编辑  收藏  举报