[英]TcpClient.GetStream().CopyTo(MemoryStream) stops application from continuing?
I'm trying to perform some extremely basic network operations, yet I'm having some trouble. 我正在尝试执行一些非常基本的网络操作,但我遇到了一些麻烦。
Originally, I was trying to use NetworkStream.Length
to create a new byte[]
, but it became apparent that this is not possible since NetworkStream
does not support seek operations. 最初,我试图使用
NetworkStream.Length
来创建一个新的byte[]
,但很明显这是不可能的,因为NetworkStream
不支持搜索操作。
I then found some examples showing how to copy the NetworkStream
to a MemoryStream
, which allows seek operations. 然后我找到了一些示例,说明如何将
NetworkStream
复制到MemoryStream
,它允许搜索操作。 So far, so good. 到现在为止还挺好。
Or is it? 或者是吗?
Once the scope of the using
statement gets hit, the application essentially stops. 一旦
using
语句的范围被命中,应用程序就会停止。 It's still running, doing something , but I can't really tell what. 它还在运行, 做某事 ,但我无法真正说出什么。 Here's the code:
这是代码:
void HandleClientComm(object client)
{
TcpClient tcpClient = (TcpClient)client;
//copy client stream to memory stream to allow seek operations
MemoryStream clientStream = new MemoryStream();
using (var clientRequestStream = tcpClient.GetStream())
{
clientRequestStream.CopyTo(clientStream);
}
//...
}
So there's where my problem has me completely stumped. 所以我的问题让我完全陷入困境。 I need to copy my
NetworkStream
to a MemoryStream
to do some processing, but this task alone is proving more difficult than it should be. 我需要将我的
NetworkStream
复制到MemoryStream
来进行一些处理,但仅此一项任务比应该更加困难。
Has anybody encountered this issue before? 以前有人遇到过这个问题吗?
A TCP stream is often not terminated - ie the inbound stream is technically alive until the socket is broken (or at a minimum : the other end of the socket elects to close their outbound link, perhaps keeping their inbound link open to get the reply). TCP流通常不会终止 - 即入站流在技术上是活动的,直到套接字被破坏(或者至少:套接字的另一端选择关闭其出站链接,可能保持其入站链接打开以获得回复) 。
Now: CopyTo
will want to read to the end of the stream. 现在:
CopyTo
将要读到流的末尾 。 Of a stream that has no end . 没有尽头的流。 The behaviour of
Read
is: Read
的行为是:
If timeouts aren't enabled, and the socket doesn't close ever, then: boom. 如果没有启用超时,并且套接字没有关闭,那么:繁荣。
For this reason, socket code usually needs to be very careful in terms of "framing" - ie knowing how much data to read as a unit. 出于这个原因,套接字代码在“框架”方面通常需要非常小心 - 即知道要将多少数据作为一个单元读取。 This is often done via some form length-prefix in the data stream, ie "the next message is 27 bytes" - then you know to only try to read 27 more bytes, because reading a 28th might block you forever.
这通常通过数据流中的某种形式长度前缀来完成,即“下一个消息是27个字节” - 然后你知道只尝试读取27个字节,因为读取第28个可能会永远阻止你。 In text-based protocols, this is often done using sentinel values like line-feed.
在基于文本的协议中,这通常使用像换行这样的标记值来完成。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.