从SslStream中读取

时间:2014-01-28 10:43:46

标签: c# tcpclient sslstream

我正在从SslStream中读取如下内容:

byte[] data = new byte[tcp.ReceiveBufferSize];
int bytesRead = -1;
do {
    bytesRead = stream.Read(data, 0, data.Length);

    using (MemoryStream ms = new MemoryStream(data, 0, bytesRead))
    using (StreamReader rd = new StreamReader(ms))
    {
        string returnData = rd.ReadToEnd();
        sb.Append(returnData);
    }
} while (bytesRead != 0);

它确实从流中读取。但是,由于流的实际长度未知,最后一次读取只会冻结应用程序。示例消息如下所示:

HTTP/1.1 200 OK
Content-Type: application/json;charset=utf-8
Content-Length: 11534
Server: Jetty(6.1.x)

{long json data here...}

服务器返回内容的长度,但它不是流的总长度。有没有一种有效的方法来成功读取此流?

1 个答案:

答案 0 :(得分:0)

我刚刚解决了同样的问题。我有一个缓冲区大小= 4096,为了防止上次读取时冻结,我们需要检查SslStream.Read是否小于缓冲区大小。如果为true,则打破读取循环,否则,我们继续读取。