javasocketsiodatainputstreamdataoutputstream

In what manner(or way) the data is being readed from the InputStream?


Client:

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();

Server:

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

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


Solution

  • The problem is on the writing end rather than the reading end.

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

    Because that is what was actually written. The write(int b) method is specified as follows:

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

    So write(0x135959) writes one byte: 0x59.

    If you want to write the int as 4 bytes, use the writeInt(int) method instead.

    If you want to write the int as 1 to 4 bytes without sending the non-significant leading zero bytes ... there isn't an API call to do that. You will need to implement it using a loop with some shifting and masking ... or similar.