首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >奇怪的SslStream缓冲问题

奇怪的SslStream缓冲问题
EN

Stack Overflow用户
提问于 2011-12-30 00:12:52
回答 1查看 863关注 0票数 1

我正在使用SslStream加密客户端和服务器之间的TCP连接。问题是,当客户端读取数据时,可能会给它提供一堆零字节,而不是真正的数据。下面是一个显示该问题的示例:

代码语言:javascript
复制
        // 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时写入的字节数完全相同。这不可能是对的这里我漏掉了什么?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2011-12-30 00:22:55

这段代码

代码语言:javascript
复制
buf = new byte[9];
stream.Read(buf, 0, buf.Length);

请求streambuf中读取1到9个字节。它并不总是准确地读取9个字节。

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

试试这个:

代码语言:javascript
复制
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);
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/8670238

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档