何时使用 TcpClient.ReceiveTimeout 与 NetworkStream.ReadTimeout?

When to use TcpClient.ReceiveTimeout vs. NetworkStream.ReadTimeout?

在编写TCP服务器时,我想设置读取客户端请求的超时时间:

var tcpClient = tcpListener.AcceptTcpClient();
var networkStream = tcpListener.GetStream();

tcpClient.ReceiveTimeout = 10000;
networkStream.ReadTimeout = 10000;

查看最后两行。我应该更喜欢哪一个?它们在有效性方面是相同的还是在哪些方面不同?

Which one should I prefer?

前者和后者都会将其内部Socket设置为接收超时。相同的套接字将从 TcpClient 冒泡到 NetworkStream 创建的,所以我会选择 前者 .

Are they equal in terms of effectivity or in which way to they differ?

还好我们可以看看source code。 这是 TcpClient.ReceiveTimeout:

public int ReceiveTimeout 
{
    get 
    {
        return numericOption(SocketOptionLevel.Socket,
                             SocketOptionName.ReceiveTimeout);
    }
    set 
    {
        Client.SetSocketOption(SocketOptionLevel.Socket,
                          SocketOptionName.ReceiveTimeout, value);
    }
}

设置底层客户端套接字的接收超时(ClientSocket 类型)。然后传递给NetworkStream:

public NetworkStream GetStream() 
{
    // Shortened for brevity
    if (m_DataStream==null)
    {
        m_DataStream = new NetworkStream(Client, true);
    }
    return m_DataStream;
}

而当 NetworkStream 查找超时时,它会在 Socket:

内部查找
public override int ReadTimeout 
{ 
    get 
    {
        int timeout = (int)m_StreamSocket.GetSocketOption(SocketOptionLevel.Socket,
                                                          SocketOptionName.ReceiveTimeout);
        if (timeout == 0) 
        {
            return -1;
        }
    }
    return timeout;
}