0

I am having a Java object and now I want to convert it into binary form (binary protocol) and send across the network and a C client will receive it and print the contents. Like I have a Student class

Student.java

import java.io.Serializable;

public class Student implements Serializable {

    public String name;
    public int id;

    public String getName() { return name; }

    public void setName(String name) { this.name = name; }

    public int getId() { return id; }

    public void setId(int id) { this.id = id; }

} 

Client.java

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.ObjectOutputStream;
import java.net.Socket;

public class Client {

    public static void main(String[] args) throws IOException {

        Student s1 = new Student();
        s1.setId(10);
        s1.setName("abc");

        Socket clientSocket = new Socket("localhost", 7777);
        DataOutputStream outToServer = new DataOutputStream(clientSocket.getOutputStream());

        try {
            FileOutputStream fos = new FileOutputStream("data.ser");
            ObjectOutputStream oos = new ObjectOutputStream(clientSocket.getOutputStream());
            oos.writeObject(s1);
            // oos.close();
            // fos.close();
        }
        catch(Exception e) {
            e.printStackTrace();
        }
        clientSocket.close();
    }

}

And the last is server.c, which is in c language.

server.c

/*
 * C socket server example
 */

#include<stdio.h>
#include<string.h>    //strlen
#include<sys/socket.h>
#include<arpa/inet.h> //inet_addr
#include<unistd.h>    //write

int main(int argc , char *argv[]) {
    int socket_desc , client_sock , c , read_size;
    struct sockaddr_in server , client;
    char client_message[2000];

    // Create socket
    socket_desc = socket(AF_INET , SOCK_STREAM , 0);
    if (socket_desc == -1) {
        printf("Could not create socket");
    }
    puts("Socket created");

    // Prepare the sockaddr_in structure
    server.sin_family = AF_INET;
    server.sin_addr.s_addr = INADDR_ANY;
    server.sin_port = htons( 7777 );

    // Bind
    if (bind(socket_desc,(struct sockaddr *)&server , sizeof(server)) < 0) {
        // Print the error message
        perror("bind failed. Error");
        return 1;
    }
    puts("bind done");

    // Listen
    listen(socket_desc , 3);

    // Accept and incoming connection
    puts("Waiting for incoming connections...");
    c = sizeof(struct sockaddr_in);

    // Accept connection from an incoming client
    client_sock = accept(socket_desc, (struct sockaddr *)&client, (socklen_t*)&c);
    if (client_sock < 0) {
        perror("accept failed");
        return 1;
    }
    puts("Connection accepted");

    // Receive a message from client
    while ((read_size = recv(client_sock , client_message , 2000 , 0)) > 0){
        // Send the message back to client
        printf("\n%s", client_message);
        write(client_sock , client_message , strlen(client_message));
    }

    if (read_size == 0) {
        puts("Client disconnected");
        fflush(stdout);
    }
    else if (read_size == -1) {
        perror("recv failed");
    }

    return 0;
}

When I am running the server and client. I am getting output like this:

 �
 sr
 xp

I want the output should be name and ID of the student printed on the server.

Please provide your suggestion or any alternate on the same.

3
  • 2
    To pass objects between different languages, you'd better use standard exchange formats like e.g XML or JSON . Commented Jan 19, 2017 at 9:32
  • ObjectOutputStream uses a Java serialization mechanism. It's not something that your C server will understand. Commented Jan 19, 2017 at 9:33
  • Via a protocol that they both understand, and Java Serialization is not one of those. Commented Jan 19, 2017 at 10:47

3 Answers 3

1

Try CBOR: RFC 7049 Concise Binary Object Representation

http://cbor.io/

Sign up to request clarification or add additional context in comments.

4 Comments

Hi @Abhijeet, I was already using Json but now I don't want to use json at all. I am looking for some binary protocol, which will convert my object state in binary and I will type cast the same using structure in c at server side,
Read the RFC http://www.rfc-base.org/txt/rfc-7049.txt. It's not json, it is a binary format.
Thanks , will read and try to implement. Just in short will it provide conversion capability of java object into c structure with same fields as java object have.
Object to binary serialization and deserialization to object is in CORBA, but that has quite some overhead. Using CBOR would require you to implement a deserializer (and serializer, if you need them there) per struct in C, but that isn't as much work as it may seem in the beginning. In Java, Jackson implementation will make it super easy for you. If you haven't decided yet, you may like to check before you finalize https://en.wikipedia.org/wiki/Comparison_of_data_serialization_formats.
0

One standard way to do this is to use CORBA and IIOP.

IIOP is a standard for transmitting binary data over the wire and is also supported by compliant Java EE implementations.

You define your objects using IDL (Interface Design Language) and then use this to generate corresponding C structs or C++ classes, Java classes or even Python classes.

You will need to set up an ORB (Object Request Broker) on the C/C++ side. There is (or used to be) a few open source versions of these around, such as OmniORB.

2 Comments

Do you have any small example of creating a object into binary (Java client side) and receive it on server side written in c and printing the values of the object. Any link for the example will also helpful.
I think you're really better off sticking to JSON if you can BTW
0

You can take a look at CORBA or Thrift, which provide basic client and server implementations for cross-language communication.

I've used both of them in the past (I prefer Thrift) and it supports data conversion between these languages (Provides API's to retrieve them as well).

However one overhead is that you need to create a contract up front (interface or idl or thrift files, which are pretty straight forward to use) as to how the objects should look like.
On building these contract, they generate jars/headerfiles which can be included in the code So you don't have to create those class files manually in java/cpp.

You can refer to the links provided for moreinfo.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.