How to receive a file via TCP that was sent using socket.FileSend method

I have a client application and a server server.

I want to send a file from one computer to another, so it looks like a socket. FileSend is exactly what I'm looking for.

But since there is no FileReceive method, what should I do on the server side to get the file? (My problem is that the file will have a variable size and will be larger than any buffer, I can create a GB order ...)

+7
source share
2 answers

On the server side, you can use TcpListener and after connecting the client, read the stream in pieces and save it to a file

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); } } } } } 

As for sending, you can take a look at the example provided in the documentation of the SendFile method.

With that, you can also take a look at a more robust solution that WCF should use. Protocols exist, such as MTOM, which are specifically optimized for sending binary data over HTTP. This is a much more reliable solution compared to reliable connectors, which are very low. You will have to handle things like file names, presumably metadata, ... things that are already factored into existing protocols.

+8
source
0
source

All Articles