title: Choosing a buffer size for a WebSocket response
body: <p>I'm writing a C# application that connects to a websocket server, and receives a JSON response of unknown size. I'm using the <a href="https://msdn.microsoft.com/en-us/library/system.net.websockets.clientwebsocket(v=vs.110).aspx" rel="noreferrer"><code>ClientWebSocket</code></a> class for this purpose. </p>
  
  <p>The only way to receive data from the client seems to be with the <code>ReceiveAsync</code> method, which takes an <code>ArraySegment&lt;byte&gt;</code> as an argument:</p>
  
  <pre><code>var client = new ClientWebSocket();
  client.ConnectAsync(new Uri($"ws://localhost:{port}"), token).Wait();
  var result = new ArraySegment&lt;byte&gt;(new byte[1000]);
  client.ReceiveAsync(result, token).Wait();
  </code></pre>
  
  <p>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. </p>
  
  <p><strong>How do I choose a buffer size without knowing the size of the response?</strong></p>