Click here to Skip to main content
15,867,308 members
Articles / Programming Languages / C# 4.0
Tip/Trick

Connecting to a C# ocket with a timeout, without using asynchronous (ConnectAsync)

Rate me:
Please Sign up or sign in to vote.
3.50/5 (2 votes)
19 Nov 2012CPOL 19.5K   6  
Connecting to a C# socket with a timeout.

Introduction

Connecting to a C# socket with a timeout, without using asynchronous (ConnectAsync).

Background 

When connecting to a socket in C# synchronously you don’t have a default timeout property. And usually if the server is down then it takes a long time to timeout. In order to overcome this I have come up with a simple solution.

Using the code 

The below block of code will allow you to connect to a socket with a timeout.

C#
private bool CheckConnectivityForProxyHost(string hostName, int port)
{
   if (string.IsNullOrEmpty(hostName))
       return false;

   bool isUp = false;
   Socket testSocket = null;

   try
   {
       testSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
       IPAddress ip = null;
       if (testSocket != null && IPAddress.TryParse(serverNameOrURL, out iP)) // Pass a Correct IP
       {
           IPEndPoint ipEndPoint = new IPEndPoint(ip, port);

           isUp = false;
          //time out 5 Sec
          CallWithTimeout(ConnectToProxyServers, 5000, testSocket, ipEndPoint);

               if (testSocket != null && testSocket.Connected)
               {
                   isUp = true;
               }
           }
       }
   }
   catch (Exception ex)
   {
       isUp = false;
   }
   finally
   {
       try
       {
           if (testSocket != null)
           {
               testSocket.Shutdown(SocketShutdown.Both);
           }
       }
       catch (Exception ex)
       {

       }
       finally
       {
           if (testSocket != null)
               testSocket.Close();
       }

   }

   return isUp;
}


private void CallWithTimeout(Action<Socket, IPEndPoint> action, 
        int timeoutMilliseconds, Socket socket, IPEndPoint ipendPoint)
{
   try
   {
       Action wrappedAction = () =>
       {
           action(socket, ipendPoint);
       };

       IAsyncResult result = wrappedAction.BeginInvoke(null, null);

       if (result.AsyncWaitHandle.WaitOne(timeoutMilliseconds))
       {
           wrappedAction.EndInvoke(result);
       }

   }
   catch (Exception ex)
   {

   }
}

private void ConnectToProxyServers(Socket testSocket, IPEndPoint ipEndPoint)
{
   try
   {
       if (testSocket == null || ipEndPoint == null)
           return;

        testSocket.Connect(ipEndPoint);

   }
   catch (Exception ex)
   {

   }
} 

///Testing the above code Add your IP and port 
bool isConnected = CheckConnectivityForProxyHost("192.168.1.100", 1010);    

Reminders 

This will work fine for .NET 4.0.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Sri Lanka Sri Lanka
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
-- There are no messages in this forum --