[英]C# How to send a 1GB file using TCP client
public void SendFile(string remoteHostIP, int remoteHostPort, string longFileName, string shortFileName)
{
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortFileName);
byte[] fileData = File.ReadAllBytes(longFileName);
byte[] clientData = new byte[4 + fileNameByte.Length + fileData.Length];
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
fileNameLen.CopyTo(clientData, 0);
fileNameByte.CopyTo(clientData, 4);
fileData.CopyTo(clientData, 4 + fileNameByte.Length);
TcpClient clientSocket = new TcpClient(remoteHostIP, remoteHostPort);
NetworkStream networkStream = clientSocket.GetStream();
networkStream.Write(clientData, 0, clientData.GetLength(0));
networkStream.Close();
}
可以使用此功能發送 1GB 文件,因為我現在嘗試發送的最大文件大小僅為 400MB。 不僅如此,還會導致“System.OutOfMemoryException”錯誤。 當我使用另一種方法將文件分成幾個部分但服務器端無法連續接收這些部分而只能接收一個部分時。
private void splitBigFile(string FileInputPath, byte[] inputArray)
{
int port = 1113;
double partSize = 104852000;
int partSize2 = 104852000;
string FolderOutputPath = "C:\\Users\\xx\\Desktop\\testing split";
string currPartPath;
string shortNameSplit;
FileStream fileStream = new FileStream(FileInputPath, FileMode.Open);
FileInfo fiSource = new FileInfo(txtFile.Text);
double sourceLength = fiSource.Length;
partNum = (int)Math.Ceiling((double)(sourceLength / partSize));
for (int i = 0; i < partNum; i++)
{
if (i == (partNum - 1))
{
partSize2 = (int)fiSource.Length - (i * 104852000);
}
currPartPath = FolderOutputPath + "\\" + fiSource.Name + "." + String.Format(@"{0:D4}", i) + ".part";
shortNameSplit = fiSource.Name + "." + String.Format(@"{0:D4}", i) + ".part";
byte[] fileNameByte = Encoding.ASCII.GetBytes(shortNameSplit);
byte[] readStream = new byte[partSize2];
byte[] concateFile = new byte[5 + fileNameByte.Length];
int ipSend = ((partNum - 1 - i) << 1);
ipSend |= 0; // for differentiate ip or file
byte[] byteSend = new byte[1];
byteSend[0] = (byte)ipSend;
fileStream.Read(readStream, 0, partSize2);
byte[] fileNameLen = BitConverter.GetBytes(fileNameByte.Length);
byteSend.CopyTo(concateFile, 0);
fileNameLen.CopyTo(concateFile, 1);
fileNameByte.CopyTo(concateFile, 5);
concateFile.CopyTo(inputArray, 0);
readStream.CopyTo(inputArray, concateFile.Length);
string ipAddress = "192.168.43.67";
int sendport = 1113;
//Task.Factory.StartNew(() => SendBigFileSize(ipAddress, sendport, inputArray[i]));
Array.Clear(readStream, 0, readStream.Length);
Array.Clear(fileNameLen, 0, fileNameLen.Length);
Array.Clear(fileNameByte, 0, fileNameByte.Length);
Array.Clear(byteSend, 0, byteSend.Length);
Array.Clear(byteSend, 0, byteSend.Length);
}
fileStream.Close();
}
當然,並不是一下子全部。 一次發送塊。
此外,最大 TCP 數據包大小為 64k,MTU 為 1500 字節。 您的巨大緩沖區也被拆分了,但是您正在使用大量內存。 而是一次從文件中讀取 32MB(安全 HDD I/O 緩沖區大小)並發送它,然后讀取下一位。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.