Java How to parse raw data from a UDP packet(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 以字节 [] 形式返回有效负载.您可以使用 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.
这篇关于Java如何从UDP数据包中解析原始数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Java如何从UDP数据包中解析原始数据
基础教程推荐
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01