我通过TCP / IP网络发送非常大的文件,该文件按预期工作。
只关注如何有效地发送它以便优化内存消耗。
以下是工作代码
Stream fileStream = File.OpenRead(tbFilename.Text);
byte[] fileBuffer = new byte[fileStream.Length];
fileStream.Read(fileBuffer, 0, (int)fileStream.Length);
// Open a TCP/IP Connection and send the data
TcpClient clientSocket = new TcpClient(tbServer.Text,8080);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(fileBuffer,0,fileBuffer.GetLength(0));
networkStream.Close();
答案 0 :(得分:2)
首先,Stream.Read
可能不会将整个文件只读取一个块,但是省略了返回值,即读取的字节数。
其次,您应该使用较小的缓冲区(例如4K)并使用它来发送文件。
const int BUFSIZE = 4096;
long transferred = 0L;
long length = fileStream.Length;
using (BinaryReader br = new BinaryReader(fileStream))
{
while (transferred < length)
{
int chunkSize = Math.Min(length - transferred, BUFSIZE);
byte[] buffer = br.ReadBytes(chunkSize);
networkStream.Write(buffer, 0, chunkSize);
transferred += chunkSize;
// here you can even report some progress to adjust a ProgressBar or something
}
}
答案 1 :(得分:2)
您可以使用Stream.CopyTo()将数据从源流复制到另一个。
CopyTo()方法使用taffer建议的临时缓冲区。
不要忘记随后刷新()网络流。
using (Stream fileStream = File.OpenRead(tbFilename.Text))
{
TcpClient clientSocket = new TcpClient(tbServer.Text, 8080);
NetworkStream networkStream = clientSocket.GetStream();
fileStream.CopyTo(networkStream);
networkStream.Flush();
networkStream.Close();
clientSocket.Close();
}