NetworkStream接收数据时,我可以配置stream.ReadTimeout
如果在配置的时间内未接收到任何数据,我将获得SocketExceptionex.SocketErrorCode=SocketError.TimedOut

发生此异常后,我可以继续使用流吗?还是有可能这种方式丢失一些字节?

示例代码:

using (TcpClient client = new TcpClient("127.0.0.1", 2000))
using (NetworkStream stream = client.GetStream())
using (StreamReader reader = new StreamReader(stream, Encoding.ASCII))
{
    stream.ReadTimeout = 5000;

    while (true)
    {
        int i;
        try
        {
            i = reader.Read();
        }
        catch (IOException ex)
        {
            SocketError socketError = SocketError.Success;
            if (ex.InnerException is SocketException)
                socketError = ((SocketException)ex.InnerException).SocketErrorCode;

            if (socketError == SocketError.TimedOut)
            {
                Console.WriteLine("no data received for 5 seconds");
                continue;
            }
            else throw;
        }
    }
}

最佳答案

我没有在.NET端找到有关此文档的任何文档,但是NetworkStream.ReadTimeout使用(在Windows上)setsockopt native 函数,并且在此函数的描述以及它的各种选项中都明确指出(在SO_RCVTIMEOSO_SNDTIMEO错误代码的描述中):

09-13 01:26