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