Send packet over UDP socket

I am trying to send the following data to a server that will use 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 an array of bytes where I will include them all:

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 an array of bytes with all the data, but I'm not sure that what I am doing is correct, and if all this data is read from the server. I really would appreciate it if you could give me advice,

Thank,

+3
source share
2 answers

First of all, you need to take care of the Endian-ness source and target machines.

Java Big-Endian

C ++ doesn't matter, you need to determine which machine (hardware / OS) is the executable program.

SO .

+4

- . String.getBytes() , .

0

Source: https://habr.com/ru/post/1793864/


All Articles