C#Socket通訊之逾時檢測

來源:互聯網
上載者:User

可以使用如下方法設定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,用戶端連結自動斷開,系統捕獲異常。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.