When the Client tries to connect to a disconnected IP address, there is a long timeout over 15 seconds... How can we reduce this timeout? What is the method to configure it?
The code I'm using to set up a socket connection is as following:
try { m_clientSocket = new Socket( AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); IPAddress ip = IPAddress.Parse(serverIp); int iPortNo = System.Convert.ToInt16(serverPort); IPEndPoint ipEnd = new IPEndPoint(ip, iPortNo); m_clientSocket.Connect(ipEnd); if (m_clientSocket.Connected) { lb_connectStatus.Text = "Connection Established"; WaitForServerData(); } } catch (SocketException se) { lb_connectStatus.Text = "Connection Failed"; MessageBox.Show(se.Message); }
Java socket timeout Answer: Just set the SO_TIMEOUT on your Java Socket, as shown in the following sample code: String serverName = "localhost"; int port = 8080; // set the socket SO timeout to 10 seconds Socket socket = openSocket(serverName, port); socket.
socket timeout — a maximum time of inactivity between two data packets when exchanging data with a server.
Some time it is necessary to increase or decrease timeouts on TCP sockets. You can use /proc/sys/net/ipv4/tcp_keepalive_time to setup new value. The number of seconds a connection needs to be idle before TCP begins sending out keep-alive probes. Keep-alives are only sent when the SO_KEEPALIVE socket option is enabled.
I found this. Simpler than the accepted answer, and works with .NET v2
Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Connect using a timeout (5 seconds) IAsyncResult result = socket.BeginConnect( sIP, iPort, null, null ); bool success = result.AsyncWaitHandle.WaitOne( 5000, true ); if ( socket.Connected ) { socket.EndConnect( result ); } else { // NOTE, MUST CLOSE THE SOCKET socket.Close(); throw new ApplicationException("Failed to connect server."); } //...
My take:
public static class SocketExtensions { /// <summary> /// Connects the specified socket. /// </summary> /// <param name="socket">The socket.</param> /// <param name="endpoint">The IP endpoint.</param> /// <param name="timeout">The timeout.</param> public static void Connect(this Socket socket, EndPoint endpoint, TimeSpan timeout) { var result = socket.BeginConnect(endpoint, null, null); bool success = result.AsyncWaitHandle.WaitOne(timeout, true); if (success) { socket.EndConnect(result); } else { socket.Close(); throw new SocketException(10060); // Connection timed out. } } }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With