1

I am using the below Async method to get response from the server. The response I get from the server varies from 1200 to 1500 bytes based on the request type. So, I can't fix the size of the buffer.

Is there any way from SslStream.ReadAsync to get the length of the original bytes received?

byte[] Buffer = new byte[1500];
await _sslStream.ReadAsync(Buffer, 0, Buffer.Length);

I tried using the below code but getting an exception saying:

This stream don't support seek operations.

await _sslStream.ReadAsync(Buffer, 0, (int)_sslStream.Length);

Earlier, I used BeginRead / EndRead. With that I get the original size of the buffer but Async await looks cleaner. So, I wanted to check whether its possible to get the length using ReadAsync.

VinothNair
  • 614
  • 1
  • 7
  • 24

1 Answers1

3

Exception says clearly:

This stream don't support seek operations.

First of all, I can't get why you can not use bigger buffer:

byte[] Buffer = new byte[1500];    
await _sslStream.ReadAsync(Buffer, 0, Buffer.Length);

If stream has less data that buffer can hold, only part of buffer will be loaded. Maybe you don't know, but you can get the value of read bytes:

byte[] Buffer = new byte[1500];    
var bytesRead = await _sslStream.ReadAsync(Buffer, 0, Buffer.Length);

Then you can create own buffer that fits exactly the length of read data:

byte[] bufferThatFitsData = new byte[bytesRead];
Array.Copy(buffer, 0, bufferThatFitsData, 0, bytesRead);

Now, bufferThatFitsData has length equal to size of stream (assuming that there is no more than 1500 bytes).

pwas
  • 3,225
  • 18
  • 40
  • Note that just calling `ReadAsync()` once might not be enough: one call could fill the buffer only partially, even if the whole stream is larger. – svick Mar 04 '16 at 15:15
  • Thanks svick, Now i wrapped my code inside a while loop byte[] response = new byte[1500]; int numRead; int offset = 0; while ((numRead = await _sslStream.ReadAsync(response, offset, response.Length)) != 0) { offset += numRead; } But getting an exception saying “Sum of offset and count cannot be greater than the length of the buffer.” In the second iteration. Can you please let me know what is the right way of implementing this for the partial buffer fill scenario. – VinothNair Mar 08 '16 at 07:01