SslStream是否等效于TcpClient.Available? [英] SslStream equivalent of TcpClient.Available?

查看:67
本文介绍了SslStream是否等效于TcpClient.Available?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据@ Len-Holgate 在此问题中的建议,m异步请求0字节读取,并在回调中通过同步读取接受字节可用字节,因为我知道数据可用并且不会阻塞.这看起来是如此高效和美妙.

Based on the advice of @Len-Holgate in this question, I'm asynchronously requesting 0-byte reads, and in the callback, accept bytes the available bytes with synchronous reads, since I know the data is available and won't block. This seems so efficient and wonderful.

但是随后我为SslStream添加了选项,该方法分崩离析.读取零字节是可以的,但是SslStream解密字节,在TcpClient的缓冲区中保留零字节计数(适当地如此),我无法确定SslStream中现在有多少字节可供读取.

But then I add the option for SslStream, and the approach falls apart. The zero-byte read is fine, but the SslStream decrypts the bytes, leaving a zero byte-count in the TcpClient's buffer (appropriately so), and I cannot determine how many bytes are now in the SslStream available for reading.

是否有一个简单的技巧?

一些代码,仅用于上下文:

Some code, just for context:

sslStream.BeginRead(this.zeroByteBuffer, 0, 0, DataAvailable, this);

在EndRead()(正确返回0)之后,DataAvailable包含:

And after the EndRead() ( which correctly returns 0 ), DataAvailable contains:

// by now this is 0, because sslStream has already consumed the bytes
available = myTcpClient.Available; 

if (0 < available) // Never occurs
{
    // this part can be distractingly complicated, but 
    // it's based on the available byte count
    sslStream.Read(...); 
}

并且由于该协议,我需要逐字节评估并解码可变字节宽度的unicode和东西.我不想异步读取字节!

And due to the protocol, I need to evaluate byte-by-byte and decode variable byte-width unicode and stuff. I don't want to have to read byte-by-byte asynchronously!

推荐答案

如果我理解正确,则您的消息由某个字符分隔,并且您已经在使用 StringBuilder 来解决这种情况.一条消息被分成多个部分.

If I understood correctly, your messages are delimited by a certain character, and you are already using a StringBuilder to cover the case when a message is fragmented into multiple pieces.

您可以考虑在读取数据时忽略定界符,在数据可用时向其中添加任何数据,然后检查本地 StringBuilder 中的定界符.找到后,您可以使用 sb.ToString(0,delimiterIndex) sb.Remove(0,delimiterIndex)提取一条消息,直到没有分隔符为止.

You could consider ignoring the delimiter when reading data, adding any data to it when it becomes available, and then inspecting the local StringBuilder for the delimiter character. When found, you can extract a single message using sb.ToString(0, delimiterIndex) and sb.Remove(0, delimiterIndex) until no delimiters remain.

这还将涵盖同时接收到两条消息的情况.

This would also cover the case when two messages are received simultaneously.

这篇关于SslStream是否等效于TcpClient.Available?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆