Sending int through socket in Java

27,503

Solution 1

Wrap your OutputStream with a DataOutputStream and then just use the writeInt() method.

Something else which may be useful is that on the other end you can wrap our InputStream in a DataInputStream and use readInt() to read an int back out.

Both classes also contain a number of other useful methods for reading and writing other raw types.

Solution 2

There are other type of streams you can use, which can directly send integers. You can use DataOutputStream. Observe,

DataOutputStream out;
try {
    //create write stream to send information
    out=new DataOutputStream(sock.getOutputStream());
} catch (IOException e) { 
    //Bail out
}

out.writeInt(5);
Share:
27,503
user174772
Author by

user174772

Updated on July 09, 2022

Comments

  • user174772
    user174772 almost 2 years

    What is the best possible way to send an int through a socket in Java? Right now I'm looking at

    sockout.write((byte)( length >> 24 ));
    sockout.write((byte)( (length << 8) >> 24 ));
    sockout.write((byte)( (length << 16) >> 24 ));
    sockout.write((byte)( (length << 24) >> 24 ));
    

    and then trying to rebuild the int from bytes on the other side, but it doesn't seem to work. Any ideas?

    Thanks.

  • Denis Tulskiy
    Denis Tulskiy over 14 years
    Only if there's also java of the other end.
  • jtahlborn
    jtahlborn about 12 years
    @DenisTulskiy - the other end could be any language. the DataOutputStream writes almost entirely language agnostic output (except the utf8 strings).
  • arkon
    arkon almost 11 years
    @jtahlborn Why are utf8 strings an exception? Isn't it all ultimately just bytes anyway?
  • Adam Batkin
    Adam Batkin almost 11 years
    @b1naryatr0phy Well, writeUTF() uses a format that isn't universal (as opposed to sending an integer, which, other than endianness is universal). That's because it sends the length (as a short, which is worrying) followed by the UTF-8 bytes. There's nothing wrong or proprietary about that format, so you just have to make sure that the other end is expecting that (as opposed to, say, sending the length as an int or sending a fixed-size string with no length marker)
  • arkon
    arkon almost 11 years
    @AdamBatkin I understand now, thanks for clarifying that for me.
  • leonbloy
    leonbloy about 7 years
    However, DataOutputStream closes wrapped stream when it's closed, which can be a problem.