Java — How to read an unknown number of bytes from an inputStream (socket/socketServer)?

后端 未结 11 1028
梦如初夏
梦如初夏 2020-12-15 07:42

Looking to read in some bytes over a socket using an inputStream. The bytes sent by the server may be of variable quantity, and the client doesn\'t know in advance the lengt

11条回答
  •  无人及你
    2020-12-15 08:15

    The simple answer is:

    byte b[] = byte[BIG_ENOUGH];
    int nosRead = sock.getInputStream().read(b);
    

    where BIG_ENOUGH is big enough.


    But in general there is a big problem with this. A single read call is not guaranteed to return all that the other end has written.

    • If the nosRead value is BIG_ENOUGH, your application has no way of knowing for sure if there are more bytes to come; the other end may have sent exactly BIG_ENOUGH bytes ... or more than BIG_ENOUGH 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 read to get the rest of the data.

    • If the nosRead value is less than BIG_ENOUGH, your application still 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 part way through sending the data.

    The best answer is that EITHER your application needs to know beforehand how many bytes to expect, OR the application protocol needs to somehow tell the application how many bytes to expect or when all bytes have been sent.

    Possible approaches are:

    • the application protocol uses fixed message sizes (not applicable to your example)
    • the application protocol message sizes are specified in message headers
    • the application protocol uses end-of-message markers
    • the application protocol is not message based, and the other end closes the connection to say that is the end.

    Without one of these strategies, your application is left to guess, and is liable to get it wrong occasionally.

    Then you use multiple read calls and (maybe) multiple buffers.

提交回复
热议问题