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

查看:182
本文介绍了在Java中通过UDP发送C ++结构的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是一个C ++程序员,需要在Java安卓应用程序和运行在PC上的C ++服务器之间建立一些UDP通信。



我需要在PC上接收包含以下内容的结构:

  int 
int
float

不幸的是,我完全失去了如何用Java做这个。 >

我需要创建一个DatagramPacket,但是构造函数只需要一个字节数组。现在使用C ++,这将是一个从一个结构到char *的容易的转换。但是这样的转换用Java是不可能的。



我创建了一个简单的类,其中有上面的字段。这似乎很好。我剩下的问题是如何把它变成一个字节数组。任何人都可以在这方面帮助一个Java的Noob?



干杯!



编辑:在执行以下操作的类中

  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();有没有更好的方法?





$ b

我宁愿不使用在Steve的回答中提到的google协议缓冲区,因为虽然它的有趣,它将需要太多的变化对其他平台实现,我真的不想这样做。

解决方案

您可以使用 Google协议缓冲区作为一种独立于语言的方式来序列化用于传输和接收的结构。 Java和C ++都是开箱即用的,Jon Skeet已经编写了一个生产就绪的C#实现。



我看到一些Protobuf在Android上使用的例子,其中包括


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.

I have structure that I need to receive on the PC that consists of the following:

int
int
float

Unfortunately I'm totally at a loss as to how I can do this with 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.

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?

Cheers!

Edit: 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.

解决方案

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.

I see a couple of examples of Protobuf in use on Android, including this.

这篇关于在Java中通过UDP发送C ++结构的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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