C # Scenarios for Socket timeout control

Source: Internet
Author: User

Prior to a project using remoting technology, when the remote address is invalid or the server is not running, accessing the remote object method takes a few 10 seconds to throw an exception. Because I am using TCP mode, I think I can use the socket to test the connection, I can know before calling the remote object method to see if the service is running. 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 (n, false);
BOOL isconnected = Sok. Connected; After the end of the event, this property can be used to know if there is a continuous success
Sok. Close ();

return isconnected;
}

private void Connectcallback (IAsyncResult asyncresult)
{
Try
{
var Sok = (Socket) asyncresult. asyncstate;
Sok. EndConnect (asyncresult);
}
Catch {}

M_event. Set ();
}
}

C # Scenarios for Socket timeout control

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.