語言

Socket.LingerState 屬性

定義

取得或設定一個值,指定是否 Socket 會延遲關閉套接字以嘗試傳送所有待處理的資料。

public:
 property System::Net::Sockets::LingerOption ^ LingerState { System::Net::Sockets::LingerOption ^ get(); void set(System::Net::Sockets::LingerOption ^ value); };
public System.Net.Sockets.LingerOption? LingerState { get; set; }
public System.Net.Sockets.LingerOption LingerState { get; set; }
member this.LingerState : System.Net.Sockets.LingerOption with get, set
Public Property LingerState As LingerOption

屬性值

一個 LingerOption 指定如何在關閉插座時停留的程序。

例外狀況

嘗試存取該套接字時發生錯誤。

該店 Socket 已經關閉。

範例

以下程式碼範例示範了該 LingerState 屬性的使用方式。

static void ConfigureTcpSocket(Socket tcpSocket)
{
    // Don't allow another socket to bind to this port.
    tcpSocket.ExclusiveAddressUse = true;

    // The socket will linger for 10 seconds after
    // Socket.Close is called.
    tcpSocket.LingerState = new LingerOption (true, 10);

    // Disable the Nagle Algorithm for this tcp socket.
    tcpSocket.NoDelay = true;

    // Set the receive buffer size to 8k
    tcpSocket.ReceiveBufferSize = 8192;

    // Set the timeout for synchronous receive methods to
    // 1 second (1000 milliseconds.)
    tcpSocket.ReceiveTimeout = 1000;

    // Set the send buffer size to 8k.
    tcpSocket.SendBufferSize = 8192;

    // Set the timeout for synchronous send methods
    // to 1 second (1000 milliseconds.)
    tcpSocket.SendTimeout = 1000;

    // Set the Time To Live (TTL) to 42 router hops.
    tcpSocket.Ttl = 42;

    Console.WriteLine("Tcp Socket configured:");

    Console.WriteLine($"  ExclusiveAddressUse {tcpSocket.ExclusiveAddressUse}");

    Console.WriteLine($"  LingerState {tcpSocket.LingerState.Enabled}, {tcpSocket.LingerState.LingerTime}");

    Console.WriteLine($"  NoDelay {tcpSocket.NoDelay}");

    Console.WriteLine($"  ReceiveBufferSize {tcpSocket.ReceiveBufferSize}");

    Console.WriteLine($"  ReceiveTimeout {tcpSocket.ReceiveTimeout}");

    Console.WriteLine($"  SendBufferSize {tcpSocket.SendBufferSize}");

    Console.WriteLine($"  SendTimeout {tcpSocket.SendTimeout}");

    Console.WriteLine($"  Ttl {tcpSocket.Ttl}");

    Console.WriteLine($"  IsBound {tcpSocket.IsBound}");

    Console.WriteLine("");
}

備註

該 LingerState 性質改變了方法的行為方式 Close 。 此特性設定後,會改變 Winsock 可重置連線的條件。 連線重置仍可能因 IP 協定行為而發生。

此特性控制連線在呼叫後保持開啟的時間長短,以及 Close 資料尚未傳送的時間。

當你呼叫方法將資料傳送給對等端時,這些資料會被放入輸出的網路緩衝區。 此特性可用來確保資料在方法斷線前 Close 已傳送至遠端主機。

要啟用延遲,請建立 LingerOption 一個包含所需值的實例,並將屬性設 LingerState 為該實例。

下表描述了該方法對該屬性可能值Close及該Enabled屬性中儲存屬性的LingerTime行為LingerState。

LingerState.Enabled LingerState.LingerTime 行為
false (停用),預設值 超時不適用(預設)。 嘗試傳送待處理的資料,直到預設 IP 協定逾時結束。
true (啟用) 非零的暫停 嘗試傳送待處理的資料直到指定的逾時結束,若失敗,Winsock 會重置連線。
true (啟用) 零暫停。 丟棄所有待處理的資料。 對於連線導向套接字(例如 TCP),Winsock 會重置連線。

IP 堆疊會根據連線的往返時間計算預設的 IP 協定逾時期。 在大多數情況下,堆疊計算的逾時比應用程式定義的逾時更為相關。 這是當 LingerState 屬性未設定時,socket 的預設行為。

當 LingerTime 屬性中 LingerState 儲存的屬性設定大於預設 IP 協定逾時值時,預設 IP 協定逾時仍會適用並覆蓋。

適用於