Send packet over UDP socket

1.7k views Asked by At

I am trying to send the following data to a server, that will be using C++:

static int user_id; // 4 Bytes
static byte state;  // 1 Byte
static String cipher_data; // 128 Bytes
static String hash;  // 128 Bytes

static final int PACKET_SIZE = 261;

public static byte [] packet = new byte [PACKET_SIZE];

I am trying to create a byte array where I will include all of them:

ByteArrayOutputStream baos = new ByteArrayOutputStream(PACKET_SIZE);
DataOutputStream dos = new DataOutputStream(baos);
dos.write(state);
dos.writeInt(user_id);
for (int i = 0; i < cipher_data.length(); i++) {
    dos.write((byte) cipher_data.charAt(i));
}
for (int i = 0; i < cipher_data.length(); i++) {
    dos.write((byte) hash.charAt(i));
}
packet = baos.toByteArray();

Now I have the byte array with all the data, but I am not sure that what I am doing is correct, and if all this data will be able to be read from the server side. I really will appreciate if you can give me some advise,

Thanks,

2

There are 2 answers

0
Ozair Kafray On BEST ANSWER

First thing you need to care about is the Endian-ness of the source and destination machines.

Java is Big-Endian

C++ does not matter, you need to determine what machine (hardware/OS) is the destination program executing on.

After that, this SO thread shall be able to get you through.

0
biziclop On

The second one is the encoding of strings. Use String.getBytes() instead of just casting characters to byte.