Skip to content

Instantly share code, notes, and snippets.

@hakkm
Last active October 6, 2025 22:37
Show Gist options
  • Save hakkm/78f5b1847a251c047fb8672de5235e84 to your computer and use it in GitHub Desktop.
Save hakkm/78f5b1847a251c047fb8672de5235e84 to your computer and use it in GitHub Desktop.
ui
package client;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
import java.util.concurrent.BlockingQueue;
public class TerminalWhatsApp extends Thread {
private final BlockingQueue<String> queue;
private final List<String> messages = new ArrayList<>();
private volatile boolean running = true;
private String userName;
// ANSI escape codes for color
private static final String GREEN = "\u001B[32m";
private static final String CYAN = "\u001B[36m";
private static final String RESET = "\u001B[0m";
public TerminalWhatsApp(BlockingQueue<String> queue, String userName) {
this.queue = queue;
this.userName = userName;
}
@Override
public void run() {
try (Scanner scanner = new Scanner(System.in)) {
clearScreen();
System.out.println(CYAN + "=== Welcome to Terminal WhatsApp ===" + RESET);
System.out.println("Type your messages below. Type 'exit' to quit.\n");
while (running) {
redrawChat(); // Always show chat before asking input
System.out.print("\n" + GREEN + userName + ": " + RESET);
String input = scanner.nextLine().trim();
if (input.isEmpty()) {
continue; // Ignore empty messages
}
if ("exit".equalsIgnoreCase(input)) {
System.out.println(CYAN + "Exiting WhatsApp..." + RESET);
running = false;
break;
}
sendMessage(input);
}
}
}
/** Add a local (user-sent) message and send it through the queue */
private synchronized void sendMessage(String message) {
messages.add(GREEN + userName + ": " + RESET + message);
try {
queue.put(message);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.err.println("Message sending interrupted.");
}
}
/** Add an incoming message (from another user) and refresh display */
public synchronized void addIncomingMessage(String sender, String message) {
messages.add(CYAN + sender + ": " + RESET + message);
redrawChat(); // Redraw the chat after receiving a message
// Always show prompt again so the user can continue typing
System.out.print("\n" + GREEN + userName + ": " + RESET);
System.out.flush();
}
/** Redraw the entire chat history */
private synchronized void redrawChat() {
clearScreen();
System.out.println(CYAN + "=== Chat ===" + RESET + "\n");
for (String msg : messages) {
System.out.println(msg);
}
System.out.flush();
}
/** Clear the terminal screen using ANSI codes */
private void clearScreen() {
System.out.print("\033[H\033[2J");
System.out.flush();
}
public String getUserName() {
return userName;
}
public void stopChat() {
running = false;
this.interrupt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment