通过 UDP 套接字发送数据包
我正在尝试将以下数据发送到将使用 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];
我正在尝试创建一个字节数组,其中将包含所有数据:
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();
现在我拥有包含所有数据的字节数组,但我不确定我所做的事情是正确的,并且所有这些数据都能够从服务器端读取。如果您能给我一些建议,我将不胜感激,
谢谢,
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,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要关心的第一件事是源计算机和目标计算机的Endian-ness。
Java 是 Big-Endian
C++没关系,您需要确定目标程序在哪台机器(硬件/操作系统)上执行。
之后,这个 SO线程应该能够让你通过。
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.
第二个是字符串的编码。使用 String.getBytes() 而不是仅仅将字符转换为字节。
The second one is the encoding of strings. Use
String.getBytes()
instead of just casting characters to byte.