以何种方式或方式从 InputStream 读取数据?

问题描述

客户:

int[] handshake_payload = {0x00,0x04,0x12A,0x01,0x06,0x135959}; //an array of hex values to be sent
        for(int n:handshake_payload)
          dataOutputStream.write(n);
        dataOutputStream.flush();

服务器:

int tag = dataInputStream.readUnsignedByte();
System.out.println("Tag:"+String.format("%02X",tag)); //prints Tag:00; this is fine
int len = dataInputStream.readUnsignedShort();
System.out.println("Len:"+String.format("%02X",len)); //prints Len: 42A,why not 412A (even when 412A
                                                       //fits in 16 bits of readUnsignedShort())
int val = dataInputStream.read();
System.out.println("Val:"+String.format("%02X",val)); //prints Val:01; fine
int valb = dataInputStream.readUnsignedByte();
System.out.println(String.format("%02X",valb)); //prints 06; fine
int vals = dataInputStream.readUnsignedByte();
System.out.println(String.format("%02X",vals)); // prints 59,how do I read this in order to get the complete value 135959,tried with readInt but throws EOFException,since end of stream reached before reading 4 bytes

为什么最后一个 readUnsignedByte() 返回 59 而不是 13 ?

解决方法

问题出在写端而不是读端。

为什么最后一个 readUnsignedByte() 返回 59 而不是 13 ?

因为那是实际写的。 write(int b) 方法为 specified,如下所示:

“将指定的字节(参数 b 的低八位)写入底层输出流。”

所以 write(0x135959) 写入一个字节:0x59

如果要将 int 写为 4 个字节,请改用 writeInt(int) 方法。

如果您想将 int 写入 1 到 4 个字节而不发送不重要的前导零字节……没有 API 调用可以做到这一点。您将需要使用带有一些移位和屏蔽的循环来实现它......或类似的。