Simple Java TCP server and problems with PHP clients

I am trying to configure a simple TCP connection on one port between a Java application that will act as a TCP server and a PHP script that will act as a client.

I will send the code for each below, but the problem is this: I can just connect and send data to the Java server. I can get this data and print it. My problem occurs when trying to send a response to php server.

When I comment on this last line php "echo socket_read ($ socket, 14, PHP_NORMAL_READ); The data goes to the Java server just fine. When I add this line back, the data doesn't even go to the Java server.

Because of this, I assume that my problem is with the way I either send data from Java, or try to get data in PHP from the server.

It hurts me a lot, any help would be greatly appreciated!

Java server:

protected ServerSocket socket; protected final int port = 9005; protected Socket connection; protected String command = new String(); protected String responseString = new String(); socket = new ServerSocket(port); while(true) { // open socket connection = socket.accept(); // get input reader InputStreamReader inputStream = new InputStreamReader(connection.getInputStream()); BufferedReader input = new BufferedReader(inputStream); // get output handler DataOutputStream response = new DataOutputStream(connection.getOutputStream()); // get input command = input.readLine(); // process input Logger.log("Command: " + command); responseString = command + " MC2 It Works!"; // send response response.writeBytes(responseString); response.flush(); response.close(); } 

PHP client:

 $address = 'example.com'; // obviously not the address I am using $port = 9005; $message = "Test"; $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_connect($socket, $address, $port) if(socket_send($socket, $message, strlen($message), MSG_EOF) != FALSE) { echo socket_read($socket, 14, PHP_NORMAL_READ); } 
+4
source share
1 answer

SOLVED: Here is a solution that I found out what the problem is. When reading data from the Java server, I read only one piece, and everything remained for everything else. Data needs to be read in a loop to get it all.

Also, the data that I sent to the Java server did not end with a new line or carriage return.

the next rewritten php client now does everything that works well

 $address = 'minecraft.kayoticgamer.com'; $port = 9005; $socket = socket_create(AF_INET, SOCK_STREAM, getprotobyname('tcp')); socket_connect($socket, $address, $port); $message .= chr(10); $status = socket_sendto($socket, $message, strlen($message), MSG_EOF, $address, $port); if($status !== FALSE) { $message = ''; $next = ''; while ($next = socket_read($socket, 4096)) { $message .= $next; } echo $message; } else { echo "Failed"; } socket_close($socket); 
+1
source

Source: https://habr.com/ru/post/1401529/


All Articles