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

后端 未结 11 1003
梦如初夏
梦如初夏 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:35

    Assuming the sender closes the stream at the end of the data:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    
    byte[] buf = new byte[4096];
    while(true) {
      int n = is.read(buf);
      if( n < 0 ) break;
      baos.write(buf,0,n);
    }
    
    byte data[] = baos.toByteArray();
    

提交回复
热议问题