1

I am currently trying to send strings via sockets between Java and c. I am able to either send a String to the client (c) from the server (java), or vice versa, but not BOTH, which is how I need to communicate between the two. In my c (client) code, as soon as I insert the read portion, the code haults.

Here are my two portions of code. It is safe to assume the connection between the sockets is successful.

java:

private void handshake(Socket s) throws IOException{
    this.out = new PrintStream(s.getOutputStream(), true);
    this.in = new BufferedReader(new InputStreamReader(s.getInputStream()));
    String key = in.readLine(); //get key from client
    if(!key.equals(CLIENTKEY)){
        System.out.println("Received incorrect client key: " + key);
        return;
    }

    System.out.println("received: " + key);
    System.out.println("sending key");
    out.println("serverKEY"); //send key to client
    System.out.println("sent");
}

c:

    int n;
    n = write(sockfd,"clientKEY",9);
    if (n < 0)
    {
      perror("ERROR writing to socket");
      exit(1);
    }
  n = read( sockfd,recvBuff,255 );
  if (n < 0)
    {
      perror("ERROR reading from socket");
      exit(1);
    }
  printf("Here is the message: %s\n",recvBuff);
1
  • Does it display an error message when it halts? If so, what is the message? Commented Nov 7, 2013 at 18:19

2 Answers 2

2

Modify your C send code:

char clientKey[] = "clientKEY\n"
n = write(sockfd,clientKey, strlen(clientKey));

It's better to use a variable for clientKey and then call strlen so you don't have to count char's manually. As Jiri pointed out, Java's readLine function is probably expecting a newline char that it's never getting so it hangs.

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

1 Comment

ah!! that was obvious. Thank you! I have to remember println() in java appends the \n character.
2

It seems to me that the C/C++ server sends a clientKEY message to the Java client. The Java client reads a line, i.e. waits till it receives the \n character from the C/C++ server. However, it is never sent by the C/C++ server and so the Java client waits... forever.

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.