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

In what manner(or way) the data is being readed from the 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 ?

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

Why is the last readUnsignedByte() returning 59 , & not 13 ?

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

"Writes the specified byte (the low eight bits of the argument b) to the underlying output stream."

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

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

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