当前位置: 动力学知识库 > 问答 > 编程问答 >

Sending a complex object from Java client to C server via Socket

问题描述:

I want to send some complex objects from a Java client to C server via a TCP Socket.

How can I do that ?

网友答案:

Fundamentally the question is, "How to serialize/deserialize objects in a language agnostic manner?" Specifically Java and C in your case. Since you'll be sending this data over a network, it is also important to take care of network order/endianness issues.

I assume you have access to both the the client and the server. This means you get to choose how to serialize the data. (If not, the answer is simple. Write to the specs of what the other is expecting)

Personally, I would use Protocol Buffers. There are Java bindings and C bindings.

If you don't like Protocol Buffers, there are other options like:

  • JSON (already mentioned)
  • YAML
  • Apache Thrift
  • XDR
  • roll your own
  • ...
网友答案:

Write the fields of the Java objects to a string (perhaps JSON), send them via TCP, and have the C program read the string and use it to initialize new C variables on the other end.

网友答案:

This question is pretty old, but just in case some one is still looking for a good solution, you can try out the protocol buffers implementation, as mentioned in the previous answer by @Adam Liss: (developers.google.com/protocol-buffers/)

In short, you define any complex message type as in your protocol implementation, and the tool generates C++/Java/Python code which can serialize and deserialize it.

For the same purpose using C code, a research project at the Technische Universität München (TUM) Germany have created a code generator in standard C, that can be used with embedded-C projects. This is fully compatible(with limitations due to C structs) with Google's protobuf implementation. This works better than the C Bindings because it does not need any library to be linked with. I had issues in getting the C Bindings to work on the embedded systems I was working with, because it needs to be linked with the support library.

This saved my (painful) day with my embedded project - passing complex network data(request-responses) between an embedded system and Android app(Java)/Desktop app(C++/Qt).

分享给朋友:
您可能感兴趣的文章:
随机阅读: