欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C# Socket連接請(qǐng)求超時(shí)機(jī)制實(shí)現(xiàn)代碼分享

 更新時(shí)間:2013年12月09日 11:12:44   投稿:zxhpj  
這篇文章主要介紹了C# Socket連接請(qǐng)求超時(shí)機(jī)制實(shí)現(xiàn),下面提供代碼分享,大家可以參考使用

.Net的System.Net.Sockets.TcpClient和System.Net.Sockets.Socket都沒有直接為Connect/BeginConnect提供超時(shí)控制機(jī)制。因此,或者發(fā)生網(wǎng)絡(luò)故障時(shí),客戶端連接請(qǐng)求會(huì)等待很長(zhǎng)一段時(shí)間,直到拋出異常。默認(rèn)的等待時(shí)間長(zhǎng)達(dá)20~30s。.Net Socket庫(kù)的SocketOptionName.SendTimeout提供了控制發(fā)送數(shù)據(jù)的超時(shí)時(shí)間,但并非本文討論的連接請(qǐng)求的超時(shí)時(shí)間。
實(shí)現(xiàn)

下面是實(shí)現(xiàn)的關(guān)鍵代碼:

復(fù)制代碼 代碼如下:

class TimeOutSocket
{
    private static bool IsConnectionSuccessful = false;
    private static Exception socketexception;
    private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);

    public static TcpClient TryConnect(IPEndPoint remoteEndPoint, int timeoutMiliSecond)
    {
        TimeoutObject.Reset();
        socketexception = null; 

        string serverip = Convert.ToString(remoteEndPoint.Address);
        int serverport = remoteEndPoint.Port;          
        TcpClient tcpclient = new TcpClient();
       
        tcpclient.BeginConnect(serverip, serverport,
            new AsyncCallback(CallBackMethod), tcpclient);

        if (TimeoutObject.WaitOne(timeoutMiliSecond, false))
        {
            if (IsConnectionSuccessful)
            {
                return tcpclient;
            }
            else
            {
                throw socketexception;
            }
        }
        else
        {
            tcpclient.Close();
            throw new TimeoutException("TimeOut Exception");
        }
    }
    private static void CallBackMethod(IAsyncResult asyncresult)
    {
        try
        {
            IsConnectionSuccessful = false;
            TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
            
            if (tcpclient.Client != null)
            {
                tcpclient.EndConnect(asyncresult);
                IsConnectionSuccessful = true;
            }
        }
        catch (Exception ex)
        {
            IsConnectionSuccessful = false;
            socketexception = ex;
        }
        finally
        {
            TimeoutObject.Set();
        }
    }
}

相關(guān)文章

最新評(píng)論