import java.io.BufferedReader; import java.io.PrintWriter; import java.util.LinkedList; // In the chat application, this doesn't really need to be a thread public class MainServerThread extends Thread { final SimpleLogger logger = new SimpleLogger("MainServerThread"); private final LinkedList clients = new LinkedList(); public synchronized void new_client(BufferedReader from_client, PrintWriter to_client) { final ClientListenerThread c = new ClientListenerThread(this, from_client, to_client); c.start(); clients.add(c); } public synchronized void client_has_disconneted(ClientListenerThread c) { clients.remove(c); } public void received_from_client(ClientListenerThread originator, String line_from_client) { String sender_name = originator.getUserName(); IncomingMessage m = new IncomingMessage(line_from_client, sender_name, originator); put(m); } private class IncomingMessage { public final String line; public final ClientListenerThread originator; public IncomingMessage(String line, String sender_name, ClientListenerThread originator) { this.line = line; this.originator = originator; } } private LinkedList inqueue = new LinkedList(); public synchronized void put(IncomingMessage m) { inqueue.addLast(m); notify(); logger.log("Efter put, kö nu " + inqueue.size()); } public synchronized IncomingMessage get() { while (inqueue.isEmpty()) { try { wait(); } catch (InterruptedException e) { logger.log("wait interrupted"); e.printStackTrace(); } } IncomingMessage b = inqueue.getFirst(); inqueue.removeFirst(); notify(); logger.log("Efter get, kö nu " + inqueue.size()); return b; } private boolean quit = false; public void run() { while (! quit) { IncomingMessage m = get(); // Will wait for a message final String line = m.line; final ClientListenerThread originator = m.originator; final String sender_name = originator.getUserName(); for (ClientListenerThread receiver : clients) { if (receiver != originator) receiver.send(sender_name + ": " + line); } } } // run } // class MainServerThread