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