Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Byte Operations and Datagrams in Java

I am trying to program a handshake type message as follows where C=Client S=Server:

C-->S: "I'd like to talk" //session initiation 
S-->C: "80"  //(n, randomly generated number)
C-->S: "81"  //(n+1)
S: "does n= (n+1)-1?" //confirms the connection.

For the purposes of this question assume that the logic above is correct. I would like the random number I generated to be a 32 bit number (i.e. 4 bytes sent in a UDP datagram). Since an int is 32 bits, I would prefer to use this data type, but I seem to run into one of two problems:

  1. When using an array of bytes, it is easy to send in a datagram but difficult to perform a simple math operation (such as subtract 1) for a 32 bit number.
  2. When using an int it is easy to perform a simple math operation, but it is difficult to convert between ints and bytes when sending back and forth between the client and server.

I found a method that can convert from an int to bytes. I found some information regarding using a Bytebuffer to convert to an int, but I'm not sure it's even correct. Is there an easier way to go about a process of sending an int in a datagram? It seems like an extraordinary amount of work to keep converting back and forth between bytes and ints.

like image 783
Matt Lick Avatar asked Mar 25 '26 01:03

Matt Lick


1 Answers

Nothing hard about any of those operations. DataInputStream and DataOutputStream take care of the stream->int->stream conversions, and ByteArrayInputStream and ByteArrayOutputStream take care of the stream->byte[]->stream conversions.

like image 130
user207421 Avatar answered Mar 26 '26 16:03

user207421



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!