在 Java 中通过 UDP 发送 C++ 结构 [英] Sending a C++ struct over UDP in Java

查看:40
本文介绍了在 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++ 结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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