我有一个客户端应用程序和一个服务器应用程序。
我想从一台机器发送一个文件到另一台机器,所以好像是socket。 FileSend方法正是我要找的。p>
但由于没有 FileReceive 方法,我应该在服务器端做什么才能接收文件? (我的问题是因为该文件的大小可变,并且比我可以创建 GB 顺序的任何缓冲区都大...)
最佳答案
在服务器端你可以使用 TcpListener连接客户端后,分块读取流并将其保存到文件中:
class Program
{
static void Main()
{
var listener = new TcpListener(IPAddress.Loopback, 11000);
listener.Start();
while (true)
{
using (var client = listener.AcceptTcpClient())
using (var stream = client.GetStream())
using (var output = File.Create("result.dat"))
{
Console.WriteLine("Client connected. Starting to receive the file");
// read the file in chunks of 1KB
var buffer = new byte[1024];
int bytesRead;
while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
}
}
}
}
就发送而言,您可以查看 SendFile 文档中提供的示例。方法。
话虽这么说,您也可以看看使用 WCF 的更强大的解决方案。有诸如 MTOM 之类的协议(protocol)专门针对通过 HTTP 发送二进制数据进行了优化。与依赖非常低级别的套接字相比,这是一个更强大的解决方案。您将不得不处理诸如文件名之类的事情,大概是元数据,......现有协议(protocol)中已经考虑到的事情。
关于c# - 如何通过 TCP 接收使用 socket.FileSend 方法发送的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8655980/