What will be the Byte[] size to use when receiving incoming stream
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
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.
It depends on the protocol. I would make the size 4k or 4096
. You should just read until Read
returns 0
.
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.
精彩评论