views:

114

answers:

3

Hey all,

Please tell me how to serialize data (like binary files) in C. And, how can i send this serialized data over sockets, so that it can be successfully received by the corresponding Java client.

Actually i want to convert this binary file into byte array so that it can be send over the sockets.

Thanks in advance.

+3  A: 

For interoperating between C and Java, you could use Google's Protocol Buffers (the Google reference implementation supports C++ and Java, and there's third party implementations for plain C).

caf
Wouldn't be simpler to just open the socket in C, read the file and send it to a java server socket in the other side? ( honest question )
OscarRyz
@OscarRyz: "Serializing data" usually implies that the data has some structure to it, that must be natively understood by both sides. Even if you're just transmitting an unstructured file, there's likely to be structured data around that - eg. file length, file name - that you also want to be understood by the recieving side.
caf
@OscarRyz: When i am using ObjectInputStream in Java to capture the data on socket then it is throwing a StreanCorruptedException and possibly it is due to deserialized data is transfered from C side.
@guptamukul: That's because you're trying to receive a Java object, but you're not sending a Java object from the C side.
OscarRyz
@OscarRyz: Thank you for solving out my doubt, actually i was sending data from C and was trying to receive it through ObjectInputStream and it was giving StreamCorruptedException.
Thank you Caf. I'll try out this thing.
A: 

Have you considered using a communication format such as JSON instead of raw byte RPC

For information on libraries which provide JSON for C & Java (More are available on the JSON site)

  1. Stack Overflow on C JSON implementation:
  2. JsonGlib (GNOME C JSON library referenced in the above link)
  3. JSON in Java

The advantages of using JSON include:

  1. Language independence
  2. Easy for machines to parse & generate
  3. Easy for humans to read and write (Protocol Buffers does NOT offer this)

JSON would be ideal in the case that you need to transmit object instances. If however you are truly dealing with flat binary files (that are not serialized objects) then Protocol Buffers by Google as suggested by caf will most likely be better suited (especially if they are large files).

NB: JSON requires that your byte content be encoded into a BASE64 string for transfer.

Syntax
Thanks a lot syntax, i'll surely try out this thing.
A: 

Both send()/recv() in C and java.lang.Socket operate seamlessly on byte arrays. So, if everything you need is just sending plain byte arrays, without any structure-specific encoding, you don't really need any serialization.

Vanya
@Vanya: yeah it solved my problem. thanks a lot.