I'm writing a C# application that connects to a websocket server, and receives a JSON response of unknown size. I'm using the ClientWebSocket
class for this purpose.
The only way to receive data from the client seems to be with the ReceiveAsync
method, which takes an ArraySegment<byte>
as an argument:
var client = new ClientWebSocket();
client.ConnectAsync(new Uri($"ws://localhost:{port}"), token).Wait();
var result = new ArraySegment<byte>(new byte[1000]);
client.ReceiveAsync(result, token).Wait();
The problem is, since I don't know how big the JSON response will be, I don't know how big to make the buffer backing that ArraySegment. In this case I've specified 1000 bytes, which is far too small, and the response is truncated. However I'm worried that if I set the buffer size to be arbitrarily large, (1,000,000 bytes?), I'll be using up more memory than I need.
How do I choose a buffer size without knowing the size of the response?