Sending a C++ struct over UDP in Java(在 Java 中通过 UDP 发送 C++ 结构)
问题描述
我是一名 C++ 程序员,需要在 java android 应用和 PC 上运行的 C++ 服务器之间建立一些 UDP 通信.
I'm a C++ programmer and have a need to set up some UDP communications between a java android app and the C++ server running on a PC.
我有需要在 PC 上接收的结构,包括以下内容:
I have structure that I need to receive on the PC that consists of the following:
int
int
float
不幸的是,我完全不知道如何使用 Java 做到这一点.
Unfortunately I'm totally at a loss as to how I can do this with Java.
我需要创建一个 DatagramPacket 但构造函数只需要一个字节数组.现在使用 C++,这将是从 struct 到 char* 的简单转换.但是,Java 无法进行这样的转换.
I need to create a DatagramPacket but the constructor only takes a byte array. Now with C++ this would be an easy cast from a struct to a char*. However casting like this is not possible with Java.
我创建了一个包含上述字段的简单类.这似乎很好.我剩下的问题是如何把它变成一个字节数组.任何人都可以在这方面帮助 Java 菜鸟吗?
I've create a simple class that has the above fields in it. That seems to be fine. My remaining issue is how to turn that into a byte array. Can anyone help a Java noob on this front?
干杯!
我在类中创建了一个函数来执行以下操作
I've created a function in the class that does the following
public byte[] GetBytes() throws IOException
{
ByteArrayOutputStream byteOut = new ByteArrayOutputStream();
DataOutputStream dataOut = new DataOutputStream( byteOut );
dataOut.writeInt( Integer.reverseBytes( int1) );
dataOut.writeInt( Integer.reverseBytes( int2 ) );
dataOut.writeFloat( float1 );
return byteOut.toByteArray();
}
有没有更好的方法来做到这一点?
Is there a better way to do this?
我宁愿不使用史蒂夫回答中提到的谷歌协议缓冲区,因为虽然它很有趣,但它需要对其他平台实现进行太多更改,而我真的不想这样做.
I'd rather not use the google protocol buffer mentioned in Steve's answer because, while its interesting, it would require too many changes to other platform implementations that I'd really rather not do.
推荐答案
你可以使用 Google 协议缓冲区作为一种独立于语言的方式来序列化用于传输和接收的结构.Java 和 C++ 都是开箱即用的,Jon Skeet 编写了一个生产就绪的 C# 实现.
You can use Google protocol buffers as a language-independent way to serialize structures for transmission and receipt. Both Java and C++ are available out of the box, and Jon Skeet has written a production-ready C# implementation.
我看到几个在 Android 上使用 Protobuf 的例子,包括 这个.
I see a couple of examples of Protobuf in use on Android, including this.
这篇关于在 Java 中通过 UDP 发送 C++ 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在 Java 中通过 UDP 发送 C++ 结构


基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01