c# – 何时使用TcpClient.ReceiveTimeout与NetworkStream.ReadTimeout?

前端之家收集整理的这篇文章主要介绍了c# – 何时使用TcpClient.ReceiveTimeout与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);
    }
}

其中设置了underling客户端套接字的接收超时(客户端的类型为Socket).然后传递给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;
}
原文链接:https://www.f2er.com/csharp/100136.html

猜你在找的C#相关文章