如何通过使用socket.FileSend方法发送的TCP文件

我有一个客户端应用程序和一个服务器。

我想从一台机器发送文件到另一台机器,所以它似乎是套接字。 FileSend方法正是我正在寻找的。

但是由于没有FileReceive方法,我应该在服务器端做什么来接收文件? (我的问题是因为文件将具有可变大小,并且将比我可以创建GB顺序的任何缓冲区大…)

在服务器端,您可以使用TcpListener,并在连接客户端后以块的forms读取流并将其保存到文件中:

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,专门针对通过HTTP发送二进制数据进行了优化。 与依赖非常低级别的套接字相比,它是一种更强大的解决方案。 您将不得不处理诸如文件名,可能是元数据之类的东西……已经在现有协议中考虑的事情。

您需要使用Socket.Receive或Socket.BeginReceive