Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to stop BufferedReader readline()?

Im new to java and im trying to make client-server form. The client and server can chat each other. So my client have 2 thread for 2 mission: send and receive message. I want when my SendThread read from keyboard string "Bye", my client will stop 2 thread. But problem is the thread receive still perform the statement readline() of BufferedReader so it can't reach to the exit Here is my code of mine:

        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 everyone because i dont explain more clearly. My client have 2 thread run independently. So ReceiveThread where this code is in can alway wait message from server. And SendThread also alway read data from keyboard. So when i type "Bye", SendThread read this string and stop client. Problem is ReceiveThread is performing readLine() so it can't stop itself.

like image 303
G.U.N Avatar asked Dec 19 '22 02:12

G.U.N


2 Answers

Shut the socket down for input, which will cause readLine() to return null, after which the read thread should close the socket.

like image 133
user207421 Avatar answered Jan 02 '23 19:01

user207421


According to the javadoc null reference will be returned when there is end of stream, so I would do this:

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 this is not helpfull see How to interrupt BufferedReader's readLine

like image 21
maskacovnik Avatar answered Jan 02 '23 19:01

maskacovnik