Kevin Furmanski
Kevin Furmanski

Reputation: 110

If inside while

PROBLEM SOLVED: I forgot to flush the PrintWriter in client.

I'm having an issue with this code. The output is 1, 2, 3, 4, 5, 5.5 but it won't reach 6 or 5.75 and I can't figure out what's wrong. It's a client/server application using sockets.

Client:

System.out.println("1");
socket = new Socket("localhost", 1035);
System.out.println("2");
br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
System.out.println("3");
pw = new PrintWriter(socket.getOutputStream());
System.out.println("4");

pw.println("hello");
String message = null;
System.out.println("5");
boolean done = false;

while(!done) {
    System.out.println("5.5");
    if((message = br.readLine()) != null) {
        System.out.println("6");
        cardname.setText(message);
        done = true;
    }
    System.out.println("5.75");
}
System.out.println("7");

Server:

        @Override
        public void run() {
            String message = null;
            boolean done = false;
            try {
                System.out.println("5.25");
                while(!done) {
                    System.out.println("5.5");
                    if((message = br.readLine()) != null) {
                        System.out.println("6");
                        String resp = handleRequest(message, sock.getInetAddress());
                        pw.println(resp);
                        pw.flush();
                        System.out.println("7");
                    }
                    System.out.println("5.75");
                }
                connDec();
            } catch(Exception ex) {ex.printStackTrace();}
        }

Upvotes: 1

Views: 638

Answers (1)

Raghav Sood
Raghav Sood

Reputation: 82583

Your code probably blocks on the readLine() call. readLine() blocks until it detects a \n or EOF, so unless your socket connection is actually sending one of those terminations, its going to wait for one.

Upvotes: 4

Related Questions