------

[ AD ] Port Monitor ( Try to use a Best WebSite Monitoring Tool )

------

C# TcpClientConnect Timeout / 연결 시간 제한 / 타임아웃 설정 /

 

 

<사용법>

TcpClient tcpClient = TimeoutSocket.Connect( ipend, timeout );

 


<설명>

Implementation of Connecting a Socket with Timeout in C#


Introduction

You will notice that neither of the two classes, System.Net.Sockets.TcpClient nor System.Net.Sockets.Socket 

has a timeout to connect a socket. 2개의 클래스는 시간제한 소켓 연결을 가지고 있지 않다.

I mean a timeout you can set. 설정할수 있는 타임아웃을 말한다.


.NET Sockets do not provide a Connect Timeout when calling the Connect/BeginConnect method 

while establishing a Synchronous/Asynchronous socket connection.

닷넷 소켓은 동기거나 비동기거나 소켓연결을 설정하는 동안 Connect/BeginConnect 함수를 호출할 연결 시간제한을 

제공하지 않는다.

Instead, connect is forced to wait a very long time before an Exception is thrown if the server it tried 

to connect to is not listening or if there is any network error.

만약, 서버가 listen 않하거나 무엇이든 네트웍 에러가 있는데 예외처리가 되기전에 매우 오랜 시간을 기다려야 한다.


The default timeout is 20 - 30 seconds.

기본 타임아웃은 20여초 가량이다.


There is an option in socket library named SocketOptionName.SendTimeout which is used for timeouts 

on Send data not initial connects.

소켓 라이브러리에 옵션.시간제한이 있으나, 이것은 전송데이타에 적용되며, 초기 연결에는 사용되지 않는다.



class TimeOutSocket

{

    private static bool IsConnectionSuccessful = false;

    private static Exception socketexception;

    private static ManualResetEvent TimeoutObject = new ManualResetEvent(false);

 

    public static TcpClient Connect(IPEndPoint remoteEndPoint, int timeoutMSec)

    {

        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(timeoutMSec, 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();

        }

    }

}

 

http://www.codeproject.com/KB/IP/TimeOutSocket.aspx

 

+ Recent posts