Java如何解析UDP数据包中的原始数据 [英] Java How to parse raw data from a UDP packet

查看:310
本文介绍了Java如何解析UDP数据包中的原始数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有来自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 将有效负载作为byte []返回。你可以使用 Arrays.copyOfRange 获取各个字段(我假设你的意思是字节,而不是):

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 和voilà,你的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.

这篇关于Java如何解析UDP数据包中的原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆