繁体   English   中英

与套接字关联的输入流正在返回字节值为 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
}

- 没有记录异常。由于没有生成与流/套接字相关的异常,我知道 java 客户端套接字没有关闭/超时。

应用程序正在遍历 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) 不需要第三方类,并且 (c) 如果流中没有剩余size字节,则抛出EOFException

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM