How do I stop BufferedReader readline ()?

Im new to java and im trying to create a client server form. Client and server can communicate with each other. So my client has 2 threads for 2nd mission: send and receive message. I want when my SendThread reads the string "Bye" from the keyboard, my client will stop 2 threads. But the problem is that the stream is still accepting the execution of the readline () BufferedReader expression, so it can't get to the exit Here is my code:

        try {
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            while (!stop) {
                String temp = br.readLine();
                if (temp.length() == 0) {
                    Thread.sleep(100);
                }
                else System.out.println(" Receiving from server: " + temp);
            }
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }

      

Update: Sorry because I won't explain more clearly. My client has 2 threads running independently. Thus, the ReceiveThread that contains this code can always wait for a message from the server. And SendThread always reads data from the keyboard too. So when I type "Bye" SendThread reads that line and stops the client. The problem is that ReceiveThread is executing readLine()

, so it cannot stop itself.

+3


source to share


4 answers


According to the javadoc, the null

link will be returned when there is the end of the stream, so I would do the following:

br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
String temp;
while ((temp=br.readLine())!=null) { //check null reference
    if (temp.length() == 0)
        Thread.sleep(100);
    else
        System.out.println(" Receiving from server: " + temp);
}

      



It's not helpful to see How to interrupt readLine of BufferedReader version

+3


source


Roll the socket down for input, which will readLine()

return null, after which the read stream must close the socket.



+4


source


Why not do the same for the client? when the server receives "bye" it sends "byebye" to the client and when the client receives this output.

On server

if (inputLine.equalsIgnoreCase("bye")) {
    out.println("byebye");
    socket.close();
    break;
}

      

And the client

if (resp.equals("byebye")) {
    break;
}

      

+2


source


Here is an example how to stop readLine () by closing the socket

    final Socket s = new Socket("localhost", 9999);
    BufferedReader r = new BufferedReader(new InputStreamReader(s.getInputStream()));

    //  this thread will close socket in a second
    new Thread() {
        public void run() {
            try {
                Thread.sleep(1000);
                s.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        };
    }.start();

    r.readLine();  

      

0


source







All Articles