gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 19:41:02 25 4
gpt4 key购买 nike

我通过 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/

最佳答案

简短的回答是,您发送一个 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;
}

关于c# - 如何通过网络流 c# 接收大文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21259703/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com