开发者

Send packet over UDP socket

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 th开发者_如何学JAVAe 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,


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.


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜