I was stuck for two days with the following problem: I wrote a Java socket server that can receive and send data to a socket hosted on "localhost: 64005". I can connect to it via php and send or receive messages. However, I cannot send and then receive a response. I traced the problem to the php script that I wrote.
<?php
class socketCommunication{
protected $PK;
protected $ip = '127.0.0.1';
protected $port = 64005;
protected $socket;
public $result;
function __construct($key){
$this->socket = socket_create(AF_INET, SOCK_STREAM, 0) or die("Could not create socket\n");
$this->result = socket_connect($this->socket, $this->ip, $this->port) or die("Could not connect to server\n");
$this->PK = $key;
$this->sendSocket();
}
function getResponse(){
$bytes = socket_recv($this->socket, $buf, 2048, MSG_WAITALL);
return $buf;
}
function sendSocket(){
$len = strlen($this->PK);
socket_send ($this->socket, $this->PK, $len, 0);
}
}
?>
<?php
include("/java/socketCommunication.php");
$object2 = new socketCommunication(100001);
echo $object2->getResponse();
?>
Java socket server:
package Server;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.concurrent.Semaphore;
import Database.Reader;
public class Receive implements Runnable {
Semaphore semaphore;
private Socket connection;
String result = "default";
public Receive(Socket conn, Semaphore sem){
this.connection = conn;
this.semaphore = sem;
}
@Override
public void run() {
try {
semaphore.acquire();
System.out.println(connection.toString());
BufferedReader in = new BufferedReader(new InputStreamReader(connection.getInputStream()));
PrintWriter out = new PrintWriter(connection.getOutputStream(), true);
String userInput;
while ((userInput = in.readLine()) != null) {
System.out.println(userInput);
Reader reader = new Reader(Integer.parseInt(userInput));
this.result = reader.getResult();
System.out.println(result);
out.println(result);
break;
}
connection.close();
in.close();
System.out.println("input is closed");
semaphore.release();
} catch (IOException | InterruptedException e) {e.printStackTrace();}
}
}
As soon as I call the sendSocket and getResponse methods in php, the page just loads endlessly. However, if I just call sendSocket or getResponse (after changing the java socket so that it will not wait for input), they will work fine.
what am I doing wrong?
Sincerely.
source
share