Search code examples
javaphpfwriteserversocketbridge

Java ServersSocket close after reading


I try and fail to create a bridge between PHP and Java. With my method, it works to send one string, but the server closes after reading the data.

This is my Class in Java:

public class Server {

private static BufferedReader inputstream;
private static BufferedWriter outputstream;
private static ServerSocket server;

public static void main(String[] args){
    System.out.println("Server gestartet");
    createServer();
}

private static void createServer() {
    try {
        server = new ServerSocket(6666);
        Socket client = server.accept();
        inputstream = new BufferedReader(new InputStreamReader(client.getInputStream()));
        outputstream = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));

        String temp = null;

        while((temp = inputstream.readLine()) != null){
            System.out.println(temp);
        }

    } catch (IOException e) {
        e.printStackTrace();
    }

    try {
        inputstream.close();
        outputstream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
  }
 }

And this is how I send the String from PHP:

<?php 
 $socket = fsockopen('localhost', 6666, $errno, $errstr, 30);

 if(!$socket){
     echo("$errno <br> $errstr");
  }

 fwrite($socket, "Hello its me\n");
 fclose($socket);
 ?>

Many thanks in advance, I hope you can help me :)


Solution

  • You have to loop server.accept() in your java code.

    In your java code, you accept client connection once, read incoming data and that's all, your application ends.

    You can accept new connections in a loop, and process data in dedicated threads. Also consider using try with resources for your streams.