与套接字关联的输入流正在返回字节值为 0 的数据

Input Stream associated with socket is returning data of byte value 0

我正在使用 Java 套接字(TCP,读取超时设置为 30 秒)与外部第三方服务器通信。 服务器数据是由特定于应用程序的数据包组成的连续流。

但是从过去几天开始,输入流正在返回表示字节值 0 的数据。

 while (connectionIsValid){
 final byte[] buffer= new byte[2];
 in.read( buffer);
  //Print buffer
 //Log line
 Byte[0] is 0 
 Byte[1] is 0

//POST processing if buffer bytes is not equal to OK.
//Other wise bypass post processing
}

- 没有异常 logged.And 因为没有生成与流/套接字相关的异常我知道 java 客户端套接字没有 closed/time 出来。

并且应用程序正在通过 while 循环。

[已更新]

    private byte[] readWrapper(InputStream stream, int totalLen ) throws IOException {
        byte[] buffer;
        byte[] bufferingBuffer = new byte[0];
        while ( totalLen != 0 ) {
            buffer = new byte[totalLen];
            final int read = stream.read( buffer );
            if(read==-1 || read==0){ 
              //throw exception
             } 
            totalLen = totalLen - read;
            buffer = ArrayUtils.subarray( buffer, 0, read );
            bufferingBuffer = ArrayUtils.addAll( bufferingBuffer, buffer );

        }
        return bufferingBuffer;
    }

你不需要那么多。 JDK 已经包含一个方法:

private byte[] readChunkedData(InputStream stream, int size) throws IOException {
    byte[] buffer = new byte[size];
    DataInputStream din = new DataInputStream(stream);
    din.readFully(buffer);
    return buffer;
}

此版本 (a) 有效 (b) 不需要 third-party 类 并且 (c) 如果没有 size 字节剩余则抛出 EOFException在信息流中。