Harieo
Harieo

Reputation: 13

Getting stuck on a While Loop using BufferedReader

I've been having a problem with using a while loop surrounding a BufferedReader in Java. I'm doing some experiments with Sockets.

My current code:

InetAddress address = InetAddress.getByName(this.IP);
        SocketAddress socketaddress = new InetSocketAddress(address, this.port);
        Socket socket = new Socket();
        socket.connect(socketaddress);

        if(socket.isConnected()){

            Executor.logger.info("Connection to proxy established!");

        }
        else {

            Executor.logger.warning("Connection to proxy failed!");
            socket.close();
            return;

        }

        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        String temp2;
        while((temp2 = in.readLine()) != null){

            Executor.logger.info("Running query says " + temp2);

        }

But no matter what I've tried the code will not progress to the next line. It does not spam my logger with anything, it just suddenly stops and gets stuck.

This is client-side only and I am not in control of the receiver server-side.

Am I doing something wrong?

Thanks for any help in advance.

Edits

The server is a command-line that accepts a command with variables and returns with a code that tells you the outcome of what you just did. However, when you first connect it returns something like message, blank line, message, blank line which is the loop currently getting stuck.

Upvotes: 0

Views: 1744

Answers (1)

Harieo
Harieo

Reputation: 13

After testing I have found an alternative variable that can be used to detect whether the BufferedReader is full or not.

If you change the ((temp2 = in.readLine()) != null) from this code:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
    BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

    String temp2;
    while((temp2 = in.readLine()) != null){

        Executor.logger.info("Running query says " + temp2);

    }

And use the boolean (in.ready()) instead:

BufferedWriter out = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
        BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));

        out.write("login " + this.user + " " + this.password);
        out.flush();

        String temp2;
        while(in.ready()){

            temp2 = in.readLine();

            Executor.logger.info("Running query says " + temp2);

        }

It will stop the loop when the BufferedRead has no more data to read and can be re-initialised again whenever necessary by copying the loop again.

Upvotes: 1

Related Questions