C # socket connection timeout control solution

Source: Internet
Author: User

C # socket connection timeout control solution

A previous project used the Remoting technology. When the remote address is invalid or the server is not running, the remote object access method will take dozens of seconds to throw an exception. Because I use the tcp mode, I can use socket to test the connection, so I can know whether the remote service is running before calling the remote object method. The Code is as follows:


Public class TcpServiceConnect
{
Protected EventWaitHandle m_event;

Public TcpServiceConnect ()
{
M_event = new EventWaitHandle (true, EventResetMode. ManualReset );
}

Public void Close ()
{
M_event.Set ();
}

Public bool TryConnect (string ip, int port)
{
M_event.Reset ();

Var point = new IPEndPoint (IPAddress. Parse (ip), port );
Var sok = new Socket (AddressFamily. InterNetwork, SocketType. Stream, ProtocolType. Tcp );
Sok. BeginConnect (point, ConnectCallBack, sok );
M_event.WaitOne (3000, false );
Bool isConnected = sok. Connected; // after the event ends, you can use this attribute to check whether the event succeeds continuously.
Sok. Close ();

Return isConnected;
}

Private void ConnectCallBack (IAsyncResult asyncresult)
{
Try
{
Var sok = (Socket) asyncresult. AsyncState;
Sok. EndConnect (asyncresult );
}
Catch {}

M_event.Set ();
}
}

Related Article

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.