C # Socket connection request Timeout mechanism implementation code sharing

Source: Internet
Author: User

  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");   &nbsp    }    }     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 ();        }    }

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.