Click here to Skip to main content
13,861,621 members
Click here to Skip to main content
Add your own
alternative version


91 bookmarked
Posted 5 Dec 2008
Licenced CPOL

Implementation of Connecting a Socket with Timeout in C#

, 5 Dec 2008
Rate this:
Please Sign up or sign in to vote.
Connect with destination machine with timeout using socket programming


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. 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. 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. The default timeout is 20 - 30 seconds. There is an option in socket library named SocketOptionName.SendTimeout which is used for timeouts on Send data not initial connects. 


I have posted this code snippet on my blog to connect with destination machine with timeout using socket programming after solving the issue for one of my projects. Many people gave thanks for that. So I think that if I post it on The Code Project, many people can get it if they need it. For that reason, I am posting it here. I know it is a very simple task and should not be an article on The Code Project.

Using the Code

Here this functionality is implemented as a class. The class is as follows:

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)
        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;
                throw socketexception;
            throw new TimeoutException("TimeOut Exception");
    private static void CallBackMethod(IAsyncResult asyncresult)
            IsConnectionSuccessful = false;
            TcpClient tcpclient = asyncresult.AsyncState as TcpClient;
            if (tcpclient.Client != null)
                IsConnectionSuccessful = true;
        catch (Exception ex)
            IsConnectionSuccessful = false;
            socketexception = ex;

Here ManualResetEvent plays the main role to implement this. It has a method WaitOne which has an overload WaitOne(TimeSpan, Boolean). According to MSDN, WaitOne(TimeSpan, Boolean) blocks the current thread until the current instance receives a signal, using a TimeSpan to measure the time interval  and specifying whether to exit the synchronization domain before the wait. 

So in the main thread, we call TimeoutObject.WaitOne(timeoutMSec, false) to block the main thread until timeout or till the signal has been  got using TimeoutObject.Set(). When waitone faces timeout, then it returns timeout exception. Otherwise socket is successfully connected or it faced any network error.

Here BeginConnect of tcpclient is used because this method does not block. After calling BeginConnect, we wait using waitone. If BeginConnect does not complete operation within timeout, then waitone will signal and TimeoutException is returned. If BeginConnect does complete operation within timeout, then it will signal ManualResetEvent using TimeoutObject.Set() from the CallBackMethod which we passed as delegate in BeginInvoke that references the CallBackMethod to invoke when the operation is complete.

Sample Code

Here a project has been attached which shows the feature “Socket Timeout Connect”.


Though it is very simple work, I have posted this because I think many people like me need this feature of socket programming. If you guys have any questions, I would love to answer.


  • Initial release – 05/12/08


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


About the Author

Razan Paul (Raju)
Software Developer (Senior) CP
Australia Australia
I am an Independent Contractor in Brisbane, Australia. For me, programming is a passion first, a hobby second, and a career third.

My Blog:

You may also be interested in...

Comments and Discussions

GeneralMy vote of 3 Pin
skyslogd13-Nov-12 0:17
memberskyslogd13-Nov-12 0:17 
BugThis is not thread safe! If you use it in a multi-threaded context, you will be very sorry. Pin
David McKenzie21-Nov-11 4:12
memberDavid McKenzie21-Nov-11 4:12 
GeneralRe: This is not thread safe! If you use it in a multi-threaded context, you will be very sorry. Pin
Member 259271824-Jan-12 6:54
memberMember 259271824-Jan-12 6:54 
GeneralIncreasing connect timeout. Pin
DUMITRU Guraliuc7-Mar-11 0:07
memberDUMITRU Guraliuc7-Mar-11 0:07 
GeneralInvalidOperationException when calling TCPClient.GetStream after AsyncConnection [modified] Pin
Yaroslav Trofimov26-Aug-09 22:43
memberYaroslav Trofimov26-Aug-09 22:43 
Generalconfiguration Pin
msvs200917-Aug-09 0:26
membermsvs200917-Aug-09 0:26 
GeneralRe: configuration Pin
Razan Paul (Raju)17-Aug-09 4:28
memberRazan Paul (Raju)17-Aug-09 4:28 
GeneralUse AsyncWaitHandle on the IAsycResult - much easier. Pin
owen3756-May-09 11:04
memberowen3756-May-09 11:04 
GeneralHi RazanPaul, nice article... Pin
Jelle Hissink9-Dec-08 9:17
memberJelle Hissink9-Dec-08 9:17 
GeneralRe: BeginConnect completion Pin
CamVis11-Dec-08 0:39
memberCamVis11-Dec-08 0:39 
GeneralRe: BeginConnect completion Pin
Jelle Hissink11-Dec-08 10:18
memberJelle Hissink11-Dec-08 10:18 
GeneralRe: BeginConnect completion Pin
CamVis11-Dec-08 11:42
memberCamVis11-Dec-08 11:42 
GeneralVery nice! Pin
clark75-Dec-08 23:20
memberclark75-Dec-08 23:20 
GeneralRe: Very nice! Pin
Razan Paul (Raju)6-Dec-08 5:06
memberRazan Paul (Raju)6-Dec-08 5:06 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web05 | 2.8.190214.1 | Last Updated 5 Dec 2008
Article Copyright 2008 by Razan Paul (Raju)
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid