可以使用如下方法設定Socket通訊端的接收或發送的逾時檢測
static void ConfigureTcpSocket(Socket tcpSocket)<br />{<br /> // Don't allow another socket to bind to this port.<br /> tcpSocket.ExclusiveAddressUse = true;</p><p> // The socket will linger for 10 seconds after<br /> // Socket.Close is called.<br /> tcpSocket.LingerState = new LingerOption (true, 10);</p><p> // Disable the Nagle Algorithm for this tcp socket.<br /> tcpSocket.NoDelay = true;</p><p> // Set the receive buffer size to 8k<br /> tcpSocket.ReceiveBufferSize = 8192;</p><p> // Set the timeout for synchronous receive methods to<br /> // 1 second (1000 milliseconds.)<br /> tcpSocket.ReceiveTimeout = 1000;</p><p> // Set the send buffer size to 8k.<br /> tcpSocket.SendBufferSize = 8192;</p><p> // Set the timeout for synchronous send methods<br /> // to 1 second (1000 milliseconds.)<br /> tcpSocket.SendTimeout = 1000;</p><p> // Set the Time To Live (TTL) to 42 router hops.<br /> tcpSocket.Ttl = 42;</p><p> Console.WriteLine("Tcp Socket configured:");</p><p> Console.WriteLine(" ExclusiveAddressUse {0}",<br /> tcpSocket.ExclusiveAddressUse);</p><p> Console.WriteLine(" LingerState {0}, {1}",<br /> tcpSocket.LingerState.Enabled,<br /> tcpSocket.LingerState.LingerTime);</p><p> Console.WriteLine(" NoDelay {0}",<br /> tcpSocket.NoDelay);</p><p> Console.WriteLine(" ReceiveBufferSize {0}",<br /> tcpSocket.ReceiveBufferSize);</p><p> Console.WriteLine(" ReceiveTimeout {0}",<br /> tcpSocket.ReceiveTimeout);</p><p> Console.WriteLine(" SendBufferSize {0}",<br /> tcpSocket.SendBufferSize);</p><p> Console.WriteLine(" SendTimeout {0}",<br /> tcpSocket.SendTimeout);</p><p> Console.WriteLine(" Ttl {0}",<br /> tcpSocket.Ttl);</p><p> Console.WriteLine(" IsBound {0}",<br /> tcpSocket.IsBound);</p><p> Console.WriteLine("");<br />}
設定逾時檢測之後,系統會在逾時之後自動將Connected屬性設定為false,用戶端連結自動斷開,系統捕獲異常。