【发布时间】:2025-12-28 07:05:06
【问题描述】:
我有一个连接到服务器的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.Read 一样,SslStream.Read 的documentation 声明count 表示要读取的最大字节数。
计数
Int32
一个Int32,包含要从此流中读取的最大字节数。
虽然它只读取这 12 个字节,但我想知道剩下的 488 个字节在哪里。
在SslStream 或TcpClient 的文档中,我找不到任何表明使用SslStream.Read 会刷新流或以其他方式清空client.Available 的内容。这样做的原因是什么(以及这在哪里记录)?
有this question 要求与TcpClient.Available 等效,这不是我所要求的。我想知道为什么会发生这种情况,这里没有介绍。
【问题讨论】:
标签: c# tcpclient networkstream sslstream