tags:

views:

74

answers:

3

Hi,

I am using socket /TcpClient to send a file to a Server as below

        NetworkStream nws = tcpClient.GetStream();

        FileStream fs;

        fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
        byte[] bytesToSend = new byte[fs.Length];
        int numBytesRead = fs.Read(bytesToSend, 0, bytesToSend.Length);
        nws.Write(bytesToSend, 0, numBytesRead);

On the server sise, I have this question.

What will be the byte[] size should I use to read the stream into?

Thanks

A: 

It depends on the protocol. I would make the size 4k or 4096. You should just read until Read returns 0.

Daniel A. White
+1  A: 

You can't determine the length of a stream, all you can do is read until you hit the end. You could send the length, first, in the stream so that the server knows how much to expect. But even then, a communication error may truncate what is sent.

Adam Ruth
A: 

The recommended buffer size is the subject of this other question.

However, this does mean that you need to read from the source stream and write to the target stream multiple times in a loop, until you reach the end of the source stream. The code might look like this (originally based on the sample code for the ZipPackage class)

  public static long CopyTo(Stream source, Stream target)
  {
     const int bufSize = 8192;
     byte[] buf = new byte[bufSize];

     long totalBytes = 0;
     int bytesRead = 0;
     while ((bytesRead = source.Read(buf, 0, bufSize)) > 0)
     {
        target.Write(buf, 0, bytesRead);
        totalBytes += bytesRead;
     }
     return totalBytes;
  }

In .NET 4.0, such code is no longer necessary. Just use the new Stream.CopyTo method.

Wim Coenen
Thank u very much for this valuable link which provides much needed info. I will work with the suggestions.once agian , Thank u
MilkBottle