【问题标题】:Send packet over UDP socket通过 UDP 套接字发送数据包
【发布时间】:2011-02-22 13:17:49
【问题描述】:

我正在尝试将以下数据发送到将使用 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();

现在我有了包含所有数据的字节数组,但我不确定我所做的是否正确,以及是否能够从服务器端读取所有这些数据。如果您能给我一些建议,我将不胜感激,

谢谢,

【问题讨论】:

    标签: java sockets bytearray dataoutputstream bytearrayoutputstream


    【解决方案1】:

    首先需要关心的是源机器和目标机器的Endian-ness

    Java 是 Big-Endian

    C++ 无所谓,您需要确定目标程序在哪台机器(硬件/操作系统)上执行。

    之后,this SO 线程应该可以让你通过。

    【讨论】:

      【解决方案2】:

      第二个是字符串的编码。使用String.getBytes() 而不是仅仅将字符转换为字节。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多