C # Socket connection Request Timeout mechanism

Source: Internet
Author: User

Introduced
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 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.

Realize
Here is the key code for implementation:

Class Timeoutsocket {private static bool isconnectionsuccessful = false; private static Exception socketexception; privat e 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 sock Etexception; } 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; The catch (Exception ex) {isconnectionsuccessful = false; socketexception = ex;} finally {Timeoutobject.set ();}} }

Here, ManualResetEvent's WaitOne (TimeSpan, Boolean) played a major role. It blocks the current thread until the ManualResetEvent object is set or exceeds the timeout time. In the code above, the current thread is blocked by the WaitOne method after calling BeginConnect, and if the connection succeeds within Timeoutmilisecond time, The Timeoutobject.set is invoked in the Callbackmethod callback, the blocked connection thread is lifted and returned, otherwise the connection thread actively closes the connection and throws the timeoutexception after the wait times out.

Original address: http://www.cnblogs.com/weidagang2046/archive/2009/02/07/1385977.html

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.