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.
Shut the socket down for input, which will cause readLine()
to return null, after which the read thread should close the socket.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With