Transferring files over TCP with CopyTo()

时光总嘲笑我的痴心妄想 提交于 2020-02-25 04:46:15

问题


I have a question regarding the CopyTo() method of the Stream class:

https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.copyto

This approach works for small file circa 15kb as I tried it, but anything higher (I tested with 2mbs, 4 mbs and so on) and it just hangs on the CopyTo() method. Can't really figure out why.

Code sample:


Server's handle client :

public void HandleClient(object c)
{
    string path = "some path";
    using (TcpClient client = (TcpClient)c)
    {
        using (NetworkStream netStream = client.GetStream())
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Create))
            {
                netStream.CopyTo(fileStream);
            }
        }
    }
}

Client send :

public void Send()
{
    IPEndPoint remoteEndPoint = new IPEndPoint(IPAddress.Parse("some address"), 12345);
    string path = "some path";

    using (TcpClient client = new TcpClient(remoteEndPoint))
    {
        using (NetworkStream netStream = client.GetStream())
        {
            using (FileStream fileStream = new FileStream(path, FileMode.Open))
            {
                fileStream.CopyTo(netStream);
            }
        }
    }
}

P.s. As I research my way into Network Programming, I often find people advising other people to switch to WCF for this kind of tasks since, apparently, WCF makes everything a lot easier. What do you guys suggest and could you provide some links for a WCF noob that would be useful in modeling a LAN file sharing application since that's what my goal is?


回答1:


I managed to solve the CopyTo() issue. The problem was that I was sending the file on the main thread so the whole application just chocked for larger files that took more than an instant to transfer.

Put the sending operation in a separate thread and tested sending up to 3 GB, works as it should. Now, is there any way I could track the progress of the CopyTo() operation? Seems to me that I can't and that I should do manual transfer if I want to track the progress.

Thanks to everyone involved :)




回答2:


I'm not sure you can do a CopyTo with a file larger than the buffer size. Maybe, you can try to write it by splitting your file every buffer size.



来源:https://stackoverflow.com/questions/22332379/transferring-files-over-tcp-with-copyto

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!