SslStream equivalent of TcpClient.Available?

岁酱吖の 提交于 2021-02-07 05:48:05

问题


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!


回答1:


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 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.



来源:https://stackoverflow.com/questions/6686356/sslstream-equivalent-of-tcpclient-available

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!