I'm trying to determine the number of bytes available to be read so I can read from the SslStream
until all data has been read. SslStream
doesn't appear to have a property or method to do this so I've been trying to use the underlying Socket
. The issue here is that the number of bytes available as reported by the Socket
doesn't match the actual amount of decrypted data that I need.
Here is my Receive method:
byte[] Receive()
{
byte[] messageBuffer = new byte[4096];
int bytesRead = 0;
using (var readData = new MemoryStream())
{
while(Client.Client.Available > 0)
{
bytesRead = Stream.Read(messageBuffer, 0, messageBuffer.Length);
readData.Write(messageBuffer, 0, bytesRead);
}
return readData.ToArray();
}
}
Client.Client
is the underlying Socket
of Stream
which is the SslStream
. Let's assume a message size of 5000 bytes. There are a couple of issues here:
- The first attempt to read
Client.Client.Available
returns 5077. This is not the correct length of the data available. - After the first call to
Stream.Read
Client.Client.Available returns 0 so I exit the loop even though I've only read 4096 since that is my buffer size. So there are 904 bytes left on the stream that haven't been read.
So it appears that after I call Stream.Read
it removes the entire data from the Socket (all 5000 bytes not just the 4096 I'm asking for), which makes sense because you need the entire message to decrypt it. But there is no way of knowing if you've gotten the entire message then because there is no SslStream.Available
or anything of the sort. So my question is how can I tell if I have received the entire decrypted message? (Or how can I get the number of bytes of the decrypted message?)
Other things I have tried:
- using
Client.Client.Poll(someLongTimeoutForTesting, SelectMode.SelectRead)
but it returns false after firstStream.Read
as well. - using
Client.GetStream().DataAvailable
again returns false after the firstStream.Read
- increasing the size of the messageBuffer to the max amount Stream.Read will return (16299, not sure why this number but when I increase the message size and buffer size above this
Stream.Read()
always returns 16299). This method works however it uses an unreasonable amount of memory because in the application it will be used in the client messages are below 4096 99.99% of the time.