0

I'm trying to transfer simple message between PHP socket and JAVA socket. The php socket successfully sends the data and is waiting for Java servers response. But on the other hand Java server's socket is still waiting for the message from PHP.

Here is the Java Code:

ServerSocket s = new ServerSocket(4280);
Socket sock = s.accept();
System.out.println("Connected");
BufferedReader br = new BufferedReader(new InputStreamReader(sock.getInputStream()));
BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(sock.getOutputStream()));
System.out.println("Reading");
String str = br.readLine();
System.out.println("Writing");
bw.write(str);

Output:

Connected

Reading

Here's the PHP code:

$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_connect($socket, "localhost", 4280);
socket_write($socket, "Hello");
echo socket_read($socket, 10);
socket_write($socket, "Lelo");
echo socket_read($socket, 10);

Output:

Browser: waiting for localhost

2 Answers 2

3

Two things that can usually cause a problem:

  • Java is utilizing the readLine() method but your not sending a linefeed and return in your PHP code.
  • Try also flushing on the PHP side.

Code:

Adding linefeed:

socket_write($socket, "Hello\r\n");
Sign up to request clarification or add additional context in comments.

Comments

1

String str = br.readLine(); expect a \n which is not sent by the PHP program.

Add this :

socket_write($socket, "Hello\n" ); // <<<=== '\n' added

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.