Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Sockets between Java and C

Gus Spain
Posts: 17
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
first of all, i�m not pretty sure if i should post it here or in a C forum, so my apologies if i do wrong.
I�m trying to communicate a java client and a C server, and it works....almost. While there�s no problem in Java sending messages and C receiveng them properly, the other way doesn�t seem to work.
This piece of code shows two ways how i tried to send the information from C back to java:
1) char *cadena;
cadena = malloc(sizeof(char)*1024);
cadena = Getdata(Buffer,Buffer2, &db);
retval = send(msgsock,cadena,sizeof(Buffer2),0);
2) retval = send(msgsock,Getdata(Buffer,Buffer2, &db),sizeof(Buffer2),0);

I don�t get any error message while sending. And here it is how i do receive in java:

BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String str;
StringBuffer text=new StringBuffer();
System.out.println("BEFORE THE IF CLAUSE");
if ((str = in.readLine())!=null)

and here�s the problem, it prints the message "BEFORE THE IF CLAUSE" but then it seems it never gets to do the readLine, like if it got stuck in that line. The strange thing is that if the C server sends a message like "FROM C TO JAVA", Java receives it fine, but then why it does not the result of the function i need?
Would someone point me in the right direction?
Stefan Wagner
Ranch Hand
Posts: 1923
Linux Postgres Database Scala
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Does your "From C to java" contain an eol?
And the output of the function not?

readLine might be waiting for the lineterminator...
William Brogden
Author and all-around good cowpoke
Posts: 13056
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I sure would stick to sending bytes in both directions, and don't depend on the Java character conversions that using a Reader and readLine implies.
After you have safely received the bytes, you can try to convert to Strings.
Also - be sure you are catching and printing any IOException thrown.
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic