如何通过网络流c#接收大文件?

时间:2014-01-21 13:34:27

标签: c# sockets xamarin transfer

我通过TCPClient和TCPListener连接2个设备,我现在只发送一个字符串,它的全部工作:

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] buffer = encoder.GetBytes("Hello Server!");
clientStream.Write(buffer, 0 , buffer.Length);
clientStream.Flush();

然后

bytesRead = clientStream.Read(message, 0, 4096);
ASCIIEncoding encoder = new ASCIIEncoding();
Console.WriteLine("Mensageee"+ encoder.GetString(message, 0, bytesRead));

但现在我需要发送一个大文件,如10mb或更多,所以我应该使用它吗?

 string doc = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        byte[] file = File.ReadAllBytes(doc + filedir)
        byte[] fileBuffer = new byte[file.Length];
        TcpClient clientSocket = new TcpClient(ip, port);
        NetworkStream networkStream = clientSocket.GetStream();
        networkStream.Write(file.ToArray(), 0, fileBuffer.GetLength(0));
        networkStream.Close();

我应该如何收到所有这些文件,然后将其保存到某个地方? 欢迎任何帮助,谢谢o /

1 个答案:

答案 0 :(得分:7)

简短的回答是,您多次发送byte[]次......

基本上,您需要使用文件的子集填充缓冲区('byte []'):

int count = fileIO.Read(buffer, 0, buffer.Length);

然后通过套接字发送缓冲区:

clientSocket.Send(buffer, 0, count);

在发送整个文件之前,只需执行这两个过程...(这将是count <= 0时)但是,服务器必须知道要读取多少字节...所以我们应该从发送Int64文件的长度。

到目前为止我们有什么......

using (var fileIO = File.OpenRead(@"C:\temp\fake.bin"))
using(var clientSocket = new System.Net.Sockets.TcpClient(ip, port).GetStream())
{
  // Send Length (Int64)
  clientSocket.Write(BitConverter.GetBytes(fileIO.Length, 0, 8));

  var buffer = new byte[1024 * 8];
  int count;
  while ((count = fileIO.Read(buffer, 0, buffer.Length)) > 0)
    clientSocket.Write(buffer, 0, count);
}

服务器端

Int64 bytesReceived = 0;
int count;
var buffer = new byte[1024*8];

// Read length - Int64
clientStream.Read(buffer, 0, 8);
Int64 numberOfBytes = BitConverter.ToInt64(buffer, 0);

using(var fileIO = File.Create("@c:\some\path"))
  while(bytesReceived < numberOfBytes && (count = clientStream.Read(buffer, 0, buffer.Length)) > 0)
  {
    fileIO.Write(buffer, 0, count);
    bytesReceived += count;
  }