C # code sharing through the Socket connection request timeout Mechanism
This article mainly introduces the implementation of the C # Socket connection request timeout mechanism. The following code is provided for your reference.
System. Net. Sockets. TcpClient and System. Net. Sockets. Socket of. Net do not directly provide timeout control mechanism for Connect/BeginConnect. Therefore, when the server is not listening, or a network failure occurs, the client connection request will be forced to wait for a long time until an exception is thrown. The default wait time is 20 ~ 30 s .. SocketOptionName. SendTimeout of the Net Socket Library provides control over the timeout time for data sending, but it is not the timeout time for connection requests discussed in this article.
Implementation
The following is the key code for implementation:
The Code is as follows:
Class TimeOutSocket
{
Private static bool IsConnectionSuccessful = false;
Private static Exception socketexception;
Private static ManualResetEvent TimeoutObject = new ManualResetEvent (false );
Public static TcpClient TryConnect (IPEndPoint remoteEndPoint, int timeoutMiliSecond)
{
TimeoutObject. Reset ();
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 (timeoutMiliSecond, false ))
{
If (IsConnectionSuccessful)
{
Return tcpclient;
}
Else
{
Throw socketexception;
}
}
Else
{
Tcpclient. Close ();
Throw new TimeoutException ("TimeOut Exception ");
}
}
Private static void CallBackMethod (IAsyncResult asyncresult)
{
Try
{
IsConnectionSuccessful = false;
TcpClient tcpclient = asyncresult. AsyncState as TcpClient;
If (tcpclient. Client! = Null)
{
Tcpclient. EndConnect (asyncresult );
IsConnectionSuccessful = true;
}
}
Catch (Exception ex)
{
IsConnectionSuccessful = false;
Socketexception = ex;
}
Finally
{
TimeoutObject. Set ();
}
}
}