使用CopyTo()通过TCP传输文件 [英] Transferring files over TCP with CopyTo()
问题描述
我对Stream类的CopyTo()方法有疑问:
I have a question regarding the CopyTo() method of the Stream class:
https://docs.microsoft.com /en-us/dotnet/api/system.io.stream.copyto
这种方法在我尝试的情况下适用于大约15kb的小文件,但适用于更高的文件(我测试了2mbs,4 mbs等),并且仅挂在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.
代码示例:
服务器的句柄客户端:
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);
}
}
}
}
客户端发送:
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.在研究网络编程的过程中,我经常发现有人建议其他人改用WCF来完成这类任务,因为WCF显然使一切变得容易得多.你们有什么建议,您能否为WCF noob提供一些链接,这些链接对建立LAN文件共享应用程序很有用,因为这就是我的目标?
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?
推荐答案
我设法解决了CopyTo()问题.问题是我在主线程上发送文件,因此整个应用程序都被塞满了较大的文件,这些文件花费了超过一瞬间的时间才能传输.
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.
将发送操作放在一个单独的线程中,并测试了高达3 GB的发送,它应该可以正常工作.现在,有什么方法可以跟踪CopyTo()操作的进度?在我看来,我不能,并且如果我想跟踪进度,应该进行手动传输.
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.
感谢所有参与的人:)
这篇关于使用CopyTo()通过TCP传输文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!