Madly Happy
Madly Happy

Reputation: 21

Why is my BufferedReader not "Ready"?

I looked up all of the BuffedReader "not ready" questions even slightly related to what I was looking for but I could not find the solution to my problem.

I have a Client and a Server sending/recieving String using the appropriate methods (i.e. BufferedReader, PrintWriter), but my BufferedReader will not work. When it hits the if loop where it checks if the BufferedReader is ready, it'll go to the else statement and do its thing. I honestly have no idea how to fix this.

Help is always appreciated and thank you for taking the time to read this.

Client Side Code:

import java.net.*;
import java.util.Scanner;
import java.io.*;
public class clientServer
{
    public static void main (String [] args) throws IOException
    {
        //Opening Statement
        System.out.println("Client/Server Program Utilizing Sockets!");
        System.out.println();

        //Opening/connected socket
        String serverAddress = "127.0.0.1";
        Socket socket = new Socket(serverAddress, 13000);

        //Checks if connection is working
        System.out.print("Connection: ");
        if(socket.isConnected()== true)
        {
            System.out.println("Working...");
            System.out.println();
        }
        else
        {
            System.err.println("Connection failed. Restart Program.");
            System.exit(0);
        }

        //PrintWriter/BufferedReader instance/declaration to input/outputstream
        PrintWriter out = new PrintWriter(socket.getOutputStream());         
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        //User input statement
        Scanner input = new Scanner (System.in);
        System.out.print("Enter any greeting[s]: ");
        String greetingInput = input.nextLine();

        out.println(greetingInput); //Sends greetingInput to outputstream
        out.flush(); //Did not turn on autoflush

        System.out.println();

        //Extra Statement
        System.out.println("Sending Data...");

        //Checking if PrintWriter has error
        System.out.println("PrintWriter: " + out.checkError());

        //Checks if BufferedReader is ready.       
        System.err.println("BufferedReader: " + in.ready());
        System.out.println();

        //If BufferedReader is ready, code will compute whatever mainServer sends
        String serverResponse = null;
        while((serverResponse = in.readLine()) != null )
        {
            if(in.ready() == true)
            {
                 serverResponse += in.readLine();
                 System.out.println(serverResponse);
            }
            else
                System.err.println("Buffer not ready!");
        }
    }
}

Server side:

import java.net.*;
import java.io.*;
import java.util.*;
public class mainServer
{
    public static void main (String [] args)throws IOException
    {
    ServerSocket echoServer = null;
    try
    {
        echoServer = new ServerSocket (13000);

            Socket socket = echoServer.accept();

            try
            {
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                PrintWriter out = new PrintWriter(socket.getOutputStream(), true);

                String clientInput = in.readLine();

                out.println("Client Input: " + clientInput);
                out.println("Server Responese: Salutations, today's a wonderfully frosty day.");
                out.flush();
            }
            catch(IOException e)
            {
                System.err.println("There was problem with BufferedReader/PrintWriter: " + e);
            }
            finally
            {
                socket.close();
            }
        }

        catch(IOException e)
        {
            System.err.println("Error with Sockets: " + e);
        }
        finally 
        {
            echoServer.close();
        }
    }
}

Results:

Client/Server Program Utilizing Sockets!

Connection: Working...

Enter any greeting[s]: Hi

Sending Data...
PrintWriter: false

BufferedReader: false
Buffer not ready!
Buffer not ready!
BUILD SUCCESSFUL (total time: 2 seconds)

Upvotes: 1

Views: 2265

Answers (2)

Stephen C
Stephen C

Reputation: 719679

@EJP's answer is spot on. I just want to add that code that attempts to use the ready() method of input streams and readers is usually broken in one way or another.

And in this case, the ready() call is not achieving anything useful. It is better to just call readLine() and let it block until a line is available.

Upvotes: 1

user207421
user207421

Reputation: 311054

Most of this code doesn't make sense.

        Socket socket = new Socket(serverAddress, 13000);

        //Checks if connection is working
        System.out.print("Connection: ");
        if(socket.isConnected()== true)

It is impossible for this test to fail. If the socket didn't connect, an exception would have been thrown and you wouldn't have reached this part of the code.

        //Checks if BufferedReader is ready.       

Why?

        //If BufferedReader is ready, code will compute whatever mainServer sends
        String serverResponse = null;
        while((serverResponse = in.readLine()) != null )
        {
            if(in.ready() == true)
            {
                 serverResponse += in.readLine();
                 System.out.println(serverResponse);
            }
            else
                System.err.println("Buffer not ready!");
        }
    }

This is all nonsense. Once you get inside the loop, you already have a line of the server's response, in serverResponse. You're then checking for more input, and appending the next line of it to serverResponse, and if there isn't more input you are treating the entire situation as though there wasn't any data at all, when there was. Given that your server sends two lines of response, all you need to do inside the loop is print out serverResponse and remove all the rest of the code. readLine() will block until data arrives, end of stream occurs, or an exception is thrown.

Your client also needs to close the socket before exiting.

NB == true and != false are redundant wherever encountered. Don't write code like this.

Upvotes: 2

Related Questions