user655561
user655561

Reputation: 679

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 ?

Upvotes: 0

Views: 1935

Answers (3)

coolbreeze
coolbreeze

Reputation: 176

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

Upvotes: 1

Pablo Maurin
Pablo Maurin

Reputation: 1490

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:

Upvotes: 4

Adam Liss
Adam Liss

Reputation: 48310

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.

Upvotes: 3

Related Questions