简体   繁体   English

如何使用UDP从C应用程序向Java应用程序发送结构

[英]How to send structure from a C application to an Java Application with UDP

I actually want to send a structure over UDP from a C application to a java application. 我实际上想通过UDP将结构从C应用程序发送到Java应用程序。

The struct looking like that : 看起来像这样的结构:

typedef struct {
type1 liste1;
type2 liste2;
type3 liste3;
type4 liste4;
}liste;

And type1,2,3,4 are also structure which include themselves others structures too. 类型1、2、3、4也是自身也包含其他结构的结构。

For now, I just send the structure like that (liste is my structure) : 现在,我只是发送这样的结构(liste是我的结构):

sendto(socketOut, &(liste), sizeof(liste), 0, (SOCKADDR *) &(recvAddrAck),sizeof(recvAddrAck));

And I get the UDP like that on the java application : 我在java应用程序上得到了类似的UDP:

DatagramSocket socket = new DatagramSocket(SERVERPORT);
byte[] buf = new byte[1500];
DatagramPacket packet = new DatagramPacket(buf, buf.length);
while (true) {
socket.receive(packet);
data = packet.getData();
}

So, my question is, how to decode data ? 所以,我的问题是,如何解码数据? I'm quite a newbe with UDP protocols, but I've made some research with my friend Google, and I found some things like htons/htonl/... for the C side, and ByteArrayInputStream/DataInputStream ... for the java side. 我是使用UDP协议的新手,但是我与朋友Google进行了一些研究,发现C方面有htons / htonl / ...,而Java则有ByteArrayInputStream / DataInputStream ...侧。 But I don't really understand how and when I have to use this things, especially for the java side. 但是我真的不明白如何以及何时必须使用这些东西,尤其是在Java方面。

Hoping my question is understandable 希望我的问题是可以理解的

Thanks 谢谢

You will need to serialize in some way. 您将需要以某种方式进行序列化。 Either manually, via some text format or XML, or if you want something more robust, look into ASN.1 / BER libraries on both sides. 通过某种文本格式或XML手动进行,或者如果您想要更强大的功能,请查看两侧的ASN.1 / BER库。

Not sure to understand, but did you take a look at DatagramPacket ? 不确定是否了解,但是您看过DatagramPacket吗?

Something like 就像是

DatagramPacket answerPacket = null;
  try { 
    byte[] buffer = new byte[REC_BUFFER_SIZE];
    answerPacket = new DatagramPacket(buffer, REC_BUFFER_SIZE);
    yourSocket.receive(answerPacket);
    log.debug("Received UDP Packet from " + answerPacket.getAddress().getHostAddress());
  } catch (SocketTimeoutException e) {
    log.debug("No Answer - Connection to DatagramSocket timed out");
  }

if (answerPacket != null && answerPacket.getLength() != 0) {
    String result = new String(answerPacket.getData());
    result = result.trim(); // remove leading and trailing whitespaces...
}

might do what you need, but it means the usage of a custom format. 也许可以满足您的需求,但这意味着要使用自定义格式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM