Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SslStream equivalent of TcpClient.Available?

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!

like image 880
Jason Kleban Avatar asked Jul 13 '11 22:07

Jason Kleban


1 Answers

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.

like image 119
C.Evenhuis Avatar answered Oct 19 '22 18:10

C.Evenhuis