简体   繁体   中英

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:

将Java对象的字段写入字符串(可能是JSON ),通过TCP发送,然后让C程序读取该字符串,并使用它在另一端初始化新的C变量。

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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