0

I have a server written in Java. Its a simple one that echoes "HELLO" when a client connects and then echoes back any reply the client sends. The code is below:

ServerSocket ss=new ServerSocket(2001);
while(true) {
  Socket s=ss.accept();
  BufferedReader in=new BufferedReader(new InputStreamReader(s.getInputStream()));
  PrintWriter out=new PrintWriter(s.getOutputStream(),true);
  out.println("HELLO");
  String msg=in.readLine();
  out.println(msg);
}

I have a PHP script that connects to the server:

<?php
  $socket=socket_create(AF_INET,SOCK_STREAM,getprotobyname('tcp'));
  socket_connect($socket,'127.0.0.1',2001);
  $msg=socket_read($socket,10);
  echo socket_write($socket,'I am the client.');
  $msg=socket_read($socket,20);
  echo $msg;
?>

I am getting the "HELLO" message from the server, and the server is also getting the "I am the client" message, but the PHP client is not getting the reply back. What am I doing wrong here?

1 Answer 1

4

in.readLine() won't return until it sees a line terminator.

Unless socket_write in PHP implicitly adds a line terminator, you'll need to do so yourself, so that the Java side sees that you've written a complete line of text.

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

4 Comments

Ok. So I need to add a newline character after my reply!
Note the op's statement that the server does get the message from php(implying that readline() has returned). Although, I still think you're right.
@chris: Ah, I'd missed that. I don't see how the OP would get the message from the client unless socket_write really adds a newline implicitly... or the PHP script has given up and closed the socket.
Agreed. I don't think readline ever really returned because socket_write doesnt add a newline or a null or anything like that.

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.