Java如何从UDP数据包中解析原始数据

2022-01-22 00:00:00 udp java

我有来自二进制形式的 UDP 连接的假设数据.

I have hypothetical data coming from a UDP connection that is in binary form.

由5个字段组成,大小为25位

Its composed of 5 fields, with a size of 25 bits

它们的偏移量如下

 1. 0-4 ID
 2. 5-10 payload
 3. 11-12 status
 4. 13-23 location
 5. 23-25 checksum

如何读取这些数据?

        DatagramSocket serverSocket = new DatagramSocket(18000);
        byte[] receiveData = new byte[1024];

        while (true)
        {
            DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
            serverSocket.receive(receivePacket);

           //not sure how I should be reading the raw binary data back in

        }

我将如何存储这些数据?

推荐答案

DatagramPacket的getData 以字节 [] 形式返回有效负载.您可以使用 Arrays.copyOfRange 获取各个字段(我假设您的问题是 bytes,而不是 bits):

DatagramPacket's getData returns the payload as a byte[]. You can use Arrays.copyOfRange to get the individual fields (I'm assuming you meant bytes in your question, not bits):

while (true) {
    DatagramPacket receivePacket = new DatagramPacket(receiveData, receiveData.length);
    serverSocket.receive(receivePacket);
    // get the entire content
    byte telegramContent[] = receivePacket.getData();
    // and slice it up:

    byte ID[] = Arrays.copyOfRange(telegramContent,0,5); 
    byte payload[] = Arrays.copyOfRange(telegramContent,6,11);
    // and so on.
}

在这一步之后,您将拥有作为单独字节数组的字段,可能需要进行一些后处理/重新组装成其他类型.在这一步中,最烦人的可能是所有 Java 的类型都是有符号的,而在许多通信协议中使用的是无符号实体,所以在这一步中要小心.

After this step you'll have your fields as individual byte arrays, probably some postprocessing/reassembly into other types will be necessary. During this step probably the most annoying thing is that all Java's types are signed whereas in many communication protocols unsigned entities are used, so be careful during this step.

您的问题中未提及,但您稍后可能需要它:用于传输的消息组合.我喜欢使用 GNU Trove 的 TByteArrayList 作为该任务您无需担心在开始之前保留正确长度的 byte[],只需复制字节或消息段,完成后调用 toArray 瞧,你的 byte[] 已经准备好传输了.

Not mentioned in your question but you might need it later on: assembly of messages for transmission. I like to use GNU Trove's TByteArrayList for that task as you don't need to worry about reserving a byte[] with the correct length before you start, just copy in bytes or message segements and once you're done call toArray and voilà, your byte[] is ready for transmission.

相关文章