This article mainly introduces the C # socket connection request Timeout mechanism implementation, the following provides code sharing, you can refer to the use of
. 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 is up to 20~30s. Net Socket Library Socketoptionname.sendtimeout provides a time-out for controlling the sending of data, but not a timeout for connection requests discussed in this article. Implementation Below 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) {&nbs P if (isconnectionsuccessful) { & nbsp return tcpclient; else &NB Sp { throw socketexception { else { &NBSP ; TcpClient. Close (); throw new TimeoutException ("TimeOut Exception");   } } private static void Callbackmethod (IAsyncResult asyncresult) { try { ISCONNECTIONSUCCE Ssful = false; TcpClient tcpclient = asyncresult. AsyncState as TcpClient; if (tcpclient. Client!= null) { TCPCLI Ent. EndConnect (asyncresult); isconnectionsuccessful = true; { catch (Exception ex) { isconnectionsuccessful = false; &NB Sp socketexception = ex; }   finally { timeoutobject.set (); } }