Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
386 views
in Technique[技术] by (71.8m points)

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

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...)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...