Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to receive a file over TCP which was sent using socket.FileSend Method

Tags:

c#

file

I have a client application, and a server one.

I want to send a file from one machine to the other, so it seems the socket.FileSend method is exactly what I'm looking for.

But since there isn't a FileReceive method what should I do on the server side in order to receive a file? (My problem is because the file will have a variable size, and will be bigger than any buffer I can create GB order...)

like image 745
RagnaRock Avatar asked Dec 28 '11 12:12

RagnaRock


2 Answers

On the server side you could use a TcpListener and once a client is connected read the stream in chunks 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 far as the sending is concerned you may take a look at the example provided in the documentation of the SendFile method.

This being said you might also take a look at a more robust solution which is to use WCF. There are protocols such as MTOM which are specifically optimized for sending binary data over HTTP. It is a much more robust solution compared to relying on sockets which are very low level. You will have to handle things like filenames, presumably metadata, ... things that are already taken into account in existing protocols.

like image 128
Darin Dimitrov Avatar answered Nov 13 '22 03:11

Darin Dimitrov


You need use Socket.Receive or Socket.BeginReceive

like image 34
Andrew Avatar answered Nov 13 '22 03:11

Andrew