views:

166

answers:

2

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);
}
A: 

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 (i.e. sender is gone) and handle it in the catch the best way that suits your needs.

VoodooChild
A: 

You will have to wrap the entire while clause in an exception handler as you won't know when/if the client disconnects and you are calling the stream reader in multiple places.

Phil Bennett