I have implemented a chat application that receives messages and redirects them to all users, because I learn about concurrent programming.
The client has two streams: one for listening to the server and the other (main stream) for recording to the server.
These are the codes used to implement this:
Main theme:
try {
Thread listener = new Thread(new Receiver(in));
listener.start();
while (listener.isAlive()) {
out.println(stdIn.readLine());
}
out.close();
in.close();
clientSocket.close();
} catch (IOException e) {
System.err.println("Error trying to send text to server" + e.getMessage());
}
Runnable for the second thread:
public class Receiver implements Runnable {
private BufferedReader in;
public Receiver(BufferedReader serverInput) {
this.in = serverInput;
}
@Override
public void run() {
String responseLine;
try {
while ((responseLine = in.readLine()) != null) {
System.out.println(responseLine);
if (responseLine.contains("Bye")) break;
}
} catch (IOException e) {
System.err.println("Erro ao receber mensagem do servidor: " + e.getMessage());
}
}
}
The client must send a message (#quit) to exit the chat, to which the server will respond with a message (Bye), which will terminate the client application.
How to stop the main thread after the receiver thread has stopped its life cycle?
isAlive(), , , #quit, , stdIn.readline(), , , .
( ) listener.join() , Thread.interrupt(), - stdIn.readline() , IO.
- , github.