The C Socket connection request timeout mechanism implements code sharing

  • 2020-05-26 10:02:20
  • OfStack

Neither System.Net.Sockets.TcpClient nor System.Net.Sockets.Socket directly provide a timeout control mechanism for Connect/BeginConnect. Therefore, when the server is not listening or there is a network failure, the client connection request is forced to wait a long time until an exception is thrown. The default wait time is up to 20~30s. SocketOptionName.SendTimeout of the.Net Socket library provides control over the timeout for sending data, but it is not the timeout for connection requests discussed in this article.
implementation

Here is the key code for the implementation:


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


Related articles: