Hi all,
I'm a C++ programmer and have a need to set up some UDP communications between a java android app and the C++ server running on a PC.
I have structure that I need to receive on the PC that consists of the following:
int
int
float
Unfortunately I'm totally at a loss as to how I can do this with Java.
I need to create a DatagramPacket but the constructor only takes a byte array. Now with C++ this would be an easy cast from a struct to a char*. However casting like this is not possible with Java.
I've create a simple class that has the above fields in it. That seems to be fine. My remaining issue is how to turn that into a byte array. Can anyone help a Java noob on this front?
Cheers!
Edit: I've created a function in the class that does the following
public byte[] GetBytes() throws IOException
{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream( byteOut );
dataOut.writeInt( Integer.reverseBytes( int1) );
dataOut.writeInt( Integer.reverseBytes( int2 ) );
dataOut.writeFloat( float1 );
return byteOut.toByteArray();
}
Is there a better way to do this?
I'd rather not use the google protocol buffer mentioned in Steve's answer because, while its interesting, it would require too many changes to other platform implementations that I'd really rather not do.