C # Socket connection Request Timeout mechanism

Source: Internet
Author: User

Razanpaul

Translator: Todd Wei

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

Introduction

You may have noticed that. Net System.Net.Sockets.TcpClient and System.Net.Sockets.Socket do not provide a time-out control mechanism directly for Connect/beginconnect. Therefore, when the server is not listening, or a network failure occurs, the client connection request is forced to wait for a long time until an exception is thrown. The default wait time of up to 20~30s. Net Socket Library Socketoptionname.sendtimeout provides control over time-outs for sending data, but is not the time-out for connection requests discussed in this article.

background

The problem started with one of my projects, and after the solution, I posted the key code on my blog. I have noticed that many people are thankful for this, so I think this is a common problem, and maybe a lot of people need to solve it.

Implement

Here is the key code for the implementation:

classTimeoutsocket
{
private static BOOL Isconnectionsuccessful = False;
private staticException socketexception;
private static ManualResetEvent Timeoutobject = new ManualResetEvent (False);

public static TcpClient Connect (IPEndPoint remoteendpoint, inttimeoutmsec)
{
Timeoutobject.reset ();
SocketException = null;

String ServerIP =convert.tostring (remoteendpoint.address);
int serverport =Remoteendpoint.port;
TcpClient TcpClient = newTcpClient ();

TcpClient. BeginConnect (ServerIP, ServerPort,
NewAsyncCallback (Callbackmethod), tcpclient);

if (Timeoutobject.waitone (Timeoutmsec, False))
{
If(isconnectionsuccessful)
{
ReturnTcpClient;
}
else
            {
ThrowSocketException;
}
}
else
        {
TcpClient. Close ();
throw new TimeoutException ("TimeOut Exception");
}
}
private static voidCallbackmethod (IAsyncResult asyncresult)
{
Try
        {
Isconnectionsuccessful= False;
TcpClient TcpClient = asyncresult. AsyncState asTcpClient;

if (tcpclient. Client! = null)
{
TcpClient. EndConnect (asyncresult);
Isconnectionsuccessful = True;
}
}
Catch(Exception ex)
{
Isconnectionsuccessful = False;
SocketException =ex;
}
Finally
        {
Timeoutobject.set ();
}
}
}

Here, ManualResetEvent's WaitOne (TimeSpan, Boolean) plays a major role. It blocks the current thread until the ManualResetEvent object is set or exceeds the timeout time. In the above code, the current thread is blocked by the WaitOne method after calling BeginConnect, if the connection succeeds within timeoutmsec time, The timeoutobject.set is called in the Callbackmethod callback, the connected thread is unblocked and returned, otherwise the connection thread actively closes the connection and throws the timeoutexception after waiting for a timeout.

Summary

Although the implementation is very simple, but perhaps a lot of people need to connect the request timeout mechanism, if there are any problems, I will try to answer for you.

C # Socket connection Request Timeout mechanism

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.