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