SslStream 相当于 TcpClient.Available?
根据 @Len-Holgate 在此问题中的建议,我正在异步请求0 字节读取,并在回调中,通过同步读取接受可用字节,因为我知道数据可用并且不会阻塞。这看起来是如此高效和美妙。
但后来我添加了 SslStream 选项,该方法就失效了。零字节读取很好,但是 SslStream 解密了字节,在 TcpClient 的缓冲区中留下了零字节计数(适当地如此),并且我无法确定 SslStream 中现在有多少字节可用于读取。
有一个简单的技巧吗?
一些代码,仅用于上下文:
sslStream.BeginRead(this.zeroByteBuffer, 0, 0, DataAvailable, this);
在 EndRead() (正确返回 0 )之后,DataAvailable 包含:
// 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 等。我不想异步地逐字节读取!
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.
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.
Is there a simple trick around this?
Some code, just for context:
sslStream.BeginRead(this.zeroByteBuffer, 0, 0, DataAvailable, this);
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(...);
}
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果我理解正确,您的消息是由某个字符分隔的,并且您已经在使用
StringBuilder
来覆盖消息分成多个部分时的情况。您可以考虑在读取数据时忽略分隔符,在数据可用时向其中添加任何数据,然后检查本地
StringBuilder
中的分隔符。找到后,您可以使用sb.ToString(0, delimiterIndex)
和sb.Remove(0, delimiterIndex)
提取单个消息,直到没有分隔符为止。这也涵盖了同时接收两条消息的情况。
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.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 usingsb.ToString(0, delimiterIndex)
andsb.Remove(0, delimiterIndex)
until no delimiters remain.This would also cover the case when two messages are received simultaneously.