Bert
Bert

Reputation: 372

Increase timeout for System.Net.Sockets.Socket connect

I need to allow for connections to a FTP server using System.Net.Sockets.Socket to take a long time - at least 30 seconds but possibly more. This code always returns as signalled but not connected after 20 seconds which is apparently the internal default:

Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IAsyncResult result = socket.BeginConnect("128.0.0.1", 99, null, null);
bool signalled = result.AsyncWaitHandle.WaitOne(60000, true);

Upvotes: 4

Views: 4391

Answers (2)

Erik Öjebo
Erik Öjebo

Reputation: 10851

Old question, but we had the same problem, so I'll post our solution here.

The WaitOne timeout can be used to force a lower timeout than the system default, but if you want to increase the timeout (i.e. to more than 20 seconds in your case) you have to change the TCP settings of the underlying operating system.

We ran into this problem on Windows, where we encountered a hard timeout limit on 21 seconds. To change this, you can use the following PowerShell command (running the PowerShell prompt as admin):

Set-NetTCPSetting -SettingName InternetCustom -MaxSynRetransmissions 4

The default value is 2, which yields an effective TCP connection timeout of about 21 seconds. A value of 3 increases the timeout to about 40 seconds, and 4 to about 90 seconds. More info can be found here.

For Linux, check out this article: http://www.sekuda.com/overriding_the_default_linux_kernel_20_second_tcp_socket_connect_timeout

Upvotes: 5

Dot_NET Pro
Dot_NET Pro

Reputation: 2123

Looks like this may be what you're looking for:http://www.codeproject.com/Articles/31514/Implementation-of-Connecting-a-Socket-with-Timeout

It seems that he's using

ManualResetEvent.WaitOne()

to block the main thread for the duration of the time-out. If

IsConnectionSuccessful

is false (i.e., the connection was not made in time or the callBack failed) when time runs out, an exception will be thrown.

Upvotes: 0

Related Questions