Search code examples
javaloopstry-catchjava-ioinputstreamreader

Java inputstreamreader try block infinite loop


I have the code below in my server, and when I run it, it will read the input from my client only once and then break out of the try block, and ultimately end the while(true) loop.

public void run() {
      while (true) {
            try {
                inputStreamReader = new InputStreamReader(clientSocket.getInputStream());
                bufferedReader = new BufferedReader(inputStreamReader); 
                message = bufferedReader.readLine();
                System.out.println("this is message from client: " + message);
            } catch (Exception e) {
                //nope
            }
       //end of while
       break;
       }
}

I want it such that my try block does not finish and that it should always be listening for any incoming messages. If I take the break statement out of the while loop, then I encounter an infinite loop where my message = null. What am I doing wrong?


Solution

  • Once a connection has been closed, there will never be a new data i.e. once readLine() returns null that is it, there is no hope there will be more data.

    What you should is read data until the connection closes. You cannot prevent the other end from disconnecting.

    You should only wrap an input stream once. If you wrap it with a buffered reader multiple times, you will lose data.

    I suggest you create your BufferedReader outside the loop and keep looping while you are getting data.

    try (BufferedReader br = new BufferedReader(new InputStreaReader(clientSOcket.getInputStream())) {
    
        for(String message; (message = br.readLine()) != null; ) {
            System.out.println("From client: " + message);
        }
    
    } catch (IOException ioe) {
        ioe.printStackTrace();
    }