gpt4 book ai didi

c# - 奇怪的 SslStream 缓冲问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:13:19 24 4
gpt4 key购买 nike

我正在使用 SslStream 来加密客户端和服务器之间的 TCP 连接。问题是当客户端读取数据时,可能会得到一堆零字节而不是真正的数据。这是显示问题的示例:

        // Server
using (NetworkStream tcpStream = client.GetStream())
{
Stream stream = tcpStream;
if (ssl)
{
SslStream sslStream = new SslStream(tcpStream, true);
sslStream.AuthenticateAsServer(cert, false, SslProtocols.Default, false);
stream = sslStream;
}

byte[] buf = new byte[] {0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x01, 0x02};
stream.Write(buf, 0, buf.Length);

buf = new byte[] {0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03, 0x03};
stream.Write(buf, 0, buf.Length);
}



// Client
using (NetworkStream tcpStream = client.GetStream())
{
Stream stream = tcpStream;
if (ssl)
{
SslStream sslStream = new SslStream(
tcpStream,
true,
delegate { return true; }
);
sslStream.AuthenticateAsClient(
"localhost",
null,
SslProtocols.Default,
false
);
stream = sslStream;
}

byte[] buf = new byte[7];
stream.Read(buf, 0, buf.Length);
// buf is 01010101010101 as expected

buf = new byte[9];
stream.Read(buf, 0, buf.Length);
// buf is 020000000000000000 instead of the expected 020303030303030303
// a subsequent read of 8 bytes will get me 0303030303030303
// if the ssl bool is set to false, then the expected data is received without the need for a third read
}

似乎只有在使用 SslStream 时,客户端才需要从流中读取与服务器写入的字节数完全相同的字节数。这不可能是对的。我在这里缺少什么?

最佳答案

这段代码

buf = new byte[9];
stream.Read(buf, 0, buf.Length);

请求 stream 将 1 到 9 个字节读入 buf。它并不总是准确读取 9 个字节。

Read Method返回实际读取的字节数。

试试这个:

byte[] buffer = new byte[9];
int offset = 0;
int count = buffer.Length;

do
{
int bytesRead = stream.Read(buffer, offset, count);
if (bytesRead == 0)
break; // end of stream
offset += bytesRead;
count -= bytesRead;
}
while (count > 0);

关于c# - 奇怪的 SslStream 缓冲问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8670238/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com