Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The simple answer is:</p> <pre><code>byte b[] = byte[BIG_ENOUGH]; int nosRead = sock.getInputStream().read(b); </code></pre> <p>where <code>BIG_ENOUGH</code> is big enough.</p> <hr> <p>But in general there is a big problem with this. The <code>read</code> method is <em>not guaranteed</em> to return all that the other end has written in a single call.</p> <ul> <li><p>If the <code>nosRead</code> value is <code>BIG_ENOUGH</code>, your application has no way of knowing for sure if there are more bytes to come; the other end may have sent exactly <code>BIG_ENOUGH</code> bytes ... or more than <code>BIG_ENOUGH</code> bytes. In the former case, you application will block (for ever) if you try to read. In the latter case, your application has to do (at least) another <code>read</code> to get the rest of the data.</p></li> <li><p>If the <code>nosRead</code> value is less than <code>BIG_ENOUGH</code>, your application <em>still</em> doesn't know. It might have received everything there is, part of the data may have been delayed (due to network packet fragmentation, network packet loss, network partition, etc), or the other end might have blocked or crashed half-way through sending the data.</p></li> </ul> <p>The best answer is that your application either needs to know beforehand how many bytes to expect, or the "application protocol" needs to somehow <em>tell</em> it how many bytes to expect ... or when all bytes have been sent. Possible approaches are:</p> <ul> <li>the application protocol uses fixed message sizes</li> <li>the application protocol message sizes are specified in message headers</li> <li>the application protocol uses end-of-message markers</li> <li>the application protocol is not message based, and the other end closes the connection to say "that's the end".</li> </ul> <p>Without one of these strategies, your application is left to guess, and is liable to get it wrong occasionally.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload