Client active wait while listening from server

109 views Asked by At

Hello I'm writing a small app client/server in java. I needed that Client was permanently listening server so I came up with a solution that involved threads, here's the code

package ClientCommunication;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Socket;
import java.util.logging.Level;
import java.util.logging.Logger;

public class Listen extends Thread {

    String fromServer;
    Socket kkSocket;
    boolean connected = true;

    Listen(Socket mysocket) {
        this.kkSocket = mysocket;
    }

    @Override

    public void run() {
        while (connected) {
            fromServer = null;
            BufferedReader in = null;
            try {
                in = new BufferedReader(new InputStreamReader(kkSocket.getInputStream()));
            } catch (IOException ex) {
                connected=false;
                Logger.getLogger(Listen.class.getName()).log(Level.SEVERE, null, ex);
            }
            try {
                while (fromServer == null) {
                    fromServer = in.readLine();
                }
            } catch (IOException ex) {
                connected=false;
                Logger.getLogger(Listen.class.getName()).log(Level.SEVERE, null, ex);
            }
            System.out.println("Received from Thread: " + fromServer);
        }
    }
}

I don't know if whether or not is a good practice doing this, and I feel is not "elegant", so can you help me with a better solution?

1

There are 1 answers

0
Mordechai On BEST ANSWER

So here's what's not elegant with your code:

  • You recreate the input stream on every read.
  • Your nested while is useless, fromServer will never be null on the second iteration. It will just hang until data is streamed. (It is different from reading from a file, got it?)

Now what? Remove the outer while loop, and in the inner loop change the condition to true (infinite); it will only terminate on exception.

One more thing, move the print statement inside the while, otherwise it won't call only after an exception.

Hope this clarifies your mind a bit.