简体   繁体   中英

StreamReader.EndOfStream produces IOException

I'm working on an application that accepts TCP connections and reads in data until an </File> marker is read and then writes that data to the filesystem. I don't want to disconnect, I want to let the client sending the data to do that so they can send multiple files in one connection.

I'm using the StreamReader.EndOfStream around my outter loop, but it throws an IOException when the client disconnects. Is there a better way to do this?

private static void RecieveAsyncStream(IAsyncResult ar)
{
    TcpListener listener = (TcpListener)ar.AsyncState;
    TcpClient client = listener.EndAcceptTcpClient(ar);

    // init the streams
    NetworkStream netStream = client.GetStream();
    StreamReader streamReader = new StreamReader(netStream);
    StreamWriter streamWriter = new StreamWriter(netStream);

    while (!streamReader.EndOfStream) // throws IOException
    {
         string file= "";
         while (file!= "</File>" && !streamReader.EndOfStream)
         {
              file += streamReader.ReadLine();
         }
         // write file to filesystem
    }
    listener.BeginAcceptTcpClient(RecieveAsyncStream, listener);
}

I would put this in the try-catch block. This way when the exception is thrown you can check on it and if it is an IOException which usually happens on a timeout; or a broken connection timeout (ie sender is gone) and handle it in the catch the best way that suits your needs.

您将必须将整个while子句包装在异常处理程序中,因为您不知道客户端何时/是否断开连接,并且您要在多个位置调用流阅读器。

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