简体   繁体   中英

PHP socket sends data but Java socket is not receiving

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

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");

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

Add this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM