简体   繁体   中英

Can I continue using a NetworkStream after an exception due to a timeout?

When receiving data from a NetworkStream , I can configure the stream.ReadTimeout .
When no data has been received within the configured time, I get a SocketException with ex.SocketErrorCode=SocketError.TimedOut .

Can I continue using the stream after this exception, or is there a chance that some bytes get lost this way?

Example code:

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;
        }
    }
}

I didn't found any documentation of this on .NET side, but NetworkStream.ReadTimeout uses (on windows) setsockopt native function, and in description of this function and it's various options it is clearly stated (in description of SO_RCVTIMEO and SO_SNDTIMEO error codes):

If a send or receive operation times out on a socket, the socket state is indeterminate, and should not be used; TCP sockets in this state have a potential for data loss, since the operation could be canceled at the same moment the operation was to be completed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM