Managing Socket Connection Timeouts in .NET Framework
Network applications often need to control the time spent waiting for a connection to a remote server. The default .NET Framework socket connection timeout can be quite lengthy (often exceeding 15 seconds), leading to delays when connecting to unresponsive hosts. This article demonstrates how to adjust this timeout for improved efficiency.
Consider the following code snippet:
<code class="language-csharp">m_clientSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // ... m_clientSocket.Connect(ipEnd);</code>
The Connect
method's default behavior is to block for up to 15 seconds. To implement a shorter timeout, we can leverage the AsyncWaitHandle
class:
<code class="language-csharp">Socket socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); // Set a 5-second connection timeout IAsyncResult result = socket.BeginConnect(sIP, iPort, null, null); bool success = result.AsyncWaitHandle.WaitOne(5000, true); // Wait for 5000 milliseconds (5 seconds) if (socket.Connected) { socket.EndConnect(result); } else { // Handle connection failure socket.Close(); throw new ApplicationException("Connection to server failed."); }</code>
This revised code initiates an asynchronous connection attempt. The WaitOne
method waits for a maximum of 5 seconds. A successful connection within this timeframe is completed with EndConnect
. If the connection fails, the socket is closed, and an exception is raised, preventing prolonged waits for unresponsive servers. This approach provides a robust and efficient method for managing socket connection timeouts in your .NET Framework applications.
The above is the detailed content of How Can I Configure Socket Connect Timeout in .NET Framework?. For more information, please follow other related articles on the PHP Chinese website!