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

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

    Here is a simpler example using ByteArrayOutputStream...

            socketInputStream = socket.getInputStream();
            int expectedDataLength = 128; //todo - set accordingly/experiment. Does not have to be precise value.
            ByteArrayOutputStream baos = new ByteArrayOutputStream(expectedDataLength);
            byte[] chunk = new byte[expectedDataLength];
            int numBytesJustRead;
            while((numBytesJustRead = socketInputStream.read(chunk)) != -1) {
                baos.write(chunk, 0, numBytesJustRead);
            }
            return baos.toString("UTF-8");
    

    However, if the server does not return a -1, you will need to detect the end of the data some other way - e.g., maybe the returned content always ends with a certain marker (e.g., ""), or you could possibly solve using socket.setSoTimeout(). (Mentioning this as it is seems to be a common problem.)

提交回复
热议问题