Click here to Skip to main content
Click here to Skip to main content
Go to top

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

, 19 Nov 2012
Rate this:
Please Sign up or sign in to vote.
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.

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)

Share

About the Author

Tyronne Thomas
Software Developer (Senior)
Sri Lanka Sri Lanka
No Biography provided

Comments and Discussions

 
-- There are no messages in this forum --
| Advertise | Privacy | Mobile
Web01 | 2.8.140922.1 | Last Updated 19 Nov 2012
Article Copyright 2012 by Tyronne Thomas
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid