views:

211

answers:

3

I was just wondering how to send an int from a Java application to a C application using sockets. I have got different C programs communicating with each other and have got the Java application retrieving data from the C application, but I can't work out sending.

The C application is acting as database, the Java application then sends a user id (a 4 digit number) to the C application, if it exists it returns that record's details.

In Java I have tried using a printWriter and DataOutputStream to send the data, printWriter produces weird symbols and DataOutputStream produces "prof_agent.so".

Any help would be appreciated as I don't have a good grasp of sockets at the moment.

+1  A: 

You can send the textual representation. So the number 123 would be sent as 3 bytes '1' '2' '3'.

R Samuel Klatchko
How would I do that
David Morris
out.write( ""+123456 ); - but thats a waste of network, give some effort to do it through bytes
ante.sabo
+1  A: 

You can use DataOutputStream.writeInt. It writes an int already in network byte order by contract.

On a C side you can call recv, or read to fill in the 4-byte buffer, and then you can use ntohl ( Network-TO-Host-Long ) to convert the value you've just read to your platform int representation.

Alexander Pogrebnyak
A: 

Try this:

Socket s = ...;
DataOutputStream out = null;
try {
    out = new DataOutputStream( s.getOutputStream() );
    out.writeInt( 123456 );
} catch ( IOException e ) {
    // TODO Handle exception
} finally {
    if ( out != null ) {
        try {
            out.close();
        } catch ( IOException e ) {
            // TODO Handle exception
        }
    }
}

It whould help if you could explain a little more what your problem is.

Manuel Darveau
I keep getting an IOException on out.writeInt(). Any idea what it could be because according to my C program there is a connection.
David Morris
Can you paste the complete stack trace?
Manuel Darveau