为什么NetworkStream.Read不设置时SslStream.Read总是将TcpClient.Available设置为0]

问题描述 投票:1回答:2
我有一个连接到服务器的TcpClient客户端,它将消息发送回该客户端。

[使用NetworkStream.Read类读取此数据时,我可以使用count参数指定要读取的字节数,读取完成后,这将使TcpClient.Available减少count。从docs

计数Int32从当前流中读取的最大字节数。

例如:

public static void ReadResponse() { if (client.Available > 0) // Assume client.Available is 500 here { byte[] buffer = new byte[12]; // I only want to read the first 12 bytes, this could be a header or something var read = 0; NetworkStream stream = client.GetStream(); while (read < buffer.Length) { read = stream.Read(buffer, 0, buffer.Length); } // breakpoint } }

[将TcpClient上可用的500的前12个字节读入buffer,在断点处检查client.Available将产生[预期] 488结果(500-12)。 

现在,当我尝试做完全相同的事情,但是这次使用SslStream时,结果对我来说是相当意外的。

public static void ReadResponse() { if (client.Available > 0) // Assume client.Available is 500 here { byte[] buffer = new byte[12]; // I only want to read the first 12 bytes, this could be a header or something var read = 0; SslStream stream = new SslStream(client.GetStream(), false, new RemoteCertificateValidationCallback(ValidateServerCertificate), null); while (read < buffer.Length) { read = stream.Read(buffer, 0, buffer.Length); } // breakpoint } }

此代码将按预期方式将前12个字节读入buffer。但是,现在在断点处检查client.Available时将产生0的结果。

类似于普通的NetworkStream.ReaddocumentationSslStream.Read指出count表示要读取的最大字节数。

计数Int32Int32,包含要从此流读取的最大字节数。

虽然它只读取这12个字节,但我不知道其余的488个字节在哪里。

SslStreamTcpClient的文档中,我找不到任何指示使用SslStream.Read刷新流或以其他方式清空client.Available的信息。这样做的原因是什么(以及在何处记录)?


this question要求与TcpClient.Available等价,这就是我要的[[not。我想知道

为什么发生这种情况,这里没有介绍。

我有一个连接到服务器的TcpClient客户端,该客户端将消息发送回客户端。当使用NetworkStream.Read类读取此数据时,我可以指定要读取的字节数...
c# tcpclient networkstream sslstream
2个回答
2
投票

此外,您读取12个字节的代码不正确,这可能会影响您所看到的内容。


1
投票
over-reads
© www.soinside.com 2019 - 2024. All rights reserved.