将 NetworkStream 复制到 MemoryStream 需要无穷 ∞ 天

Copying NetworkStream to MemoryStream takes infitity ∞ days(将 NetworkStream 复制到 MemoryStream 需要无穷 ∞ 天)

本文介绍了将 NetworkStream 复制到 MemoryStream 需要无穷 ∞ 天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

_clientRequestStream = _tcpClient.GetStream();

var memoryStream = new MemoryStream();
_clientRequestStream.CopyTo(memoryStream);

CopyTo 需要很长时间才能将 Stream 复制到另一个 Stream.似乎应用程序无缘无故地停在那里,或者至少我找不到原因.

CopyTo takes long long long time to copy a Stream into another Stream. It seems application stops there without any reason or at least I couldn't find the reason.

推荐答案

网络流保持打开状态,直到它被流的一端关闭.CopyTo() 复制流中的所有数据,等待流结束.如果服务器没有发送数据,则流不会结束或关闭,CopyTo() 会尽职尽责地等待更多数据或流结束.流的另一端的服务器必须关闭流才能结束并返回 CopyTo().

A network stream remains open until it is closed by one end of the stream. CopyTo() copies all data from the stream, waiting until the stream ends. If the server is not sending data, the stream does not end or close and CopyTo() dutifully waits for more data or for the stream to end. The server on the other end of the stream must close the stream for it to end and CopyTo() to return.

谷歌TcpClient 教程"或TcpCLient 示例"以获得一些显示您可能使用它们的其他方式的好页面,例如检查 NetworkStream.DataAvailable 以查看是否有数据等待或流是否仍然打开而没有数据.要仅读取一些数据而不等待流关闭,您可以使用 NetworkStream.Read() 或将其包装在 StreamReader 中并使用 ReadLine().这完全取决于您要连接的服务器以及您要完成的任务.

Google "TcpClient Tutorial" or "TcpCLient Sample" to get some good pages showing other ways you might use them, such as checking NetworkStream.DataAvailable to see if there is data waiting or if the stream is still open with no data. To just read some data and not wait for the stream to close you would use NetworkStream.Read() or wrap it in a StreamReader and use ReadLine(). It all depends on the server you are connecting to and what you are trying to accomplish.

这篇关于将 NetworkStream 复制到 MemoryStream 需要无穷 ∞ 天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:将 NetworkStream 复制到 MemoryStream 需要无穷 ∞ 天

基础教程推荐