ChatConnectionListener.java


Below is the syntax highlighted version of ChatConnectionListener.java from §8.4 Operating Systems.


/******************************************************************************
 *  Compilation:  javac ChatConnectionListener.java
 *  Dependencies: ChatConnection.java
 *
 ******************************************************************************/

import java.util.Vector;

public class ChatConnectionListener extends Thread {
    private Vector<ChatConnection> connections;

    public ChatConnectionListener(Vector<ChatConnection> connections) {
        this.connections = connections;
    }

    // check for incoming messages and broadcast
    public void run() {
        while (true) {
            for (int i = 0; i < connections.size(); i++) {
                ChatConnection ith = connections.get(i);

                // if connection terminated, remove from list of active connections
                if (!ith.isAlive())
                    connections.remove(i);

                // broadcast to everyone
                String message = ith.getMessage();
                if (message != null)
                    for (ChatConnection jth : connections)
                        jth.println(message);

            }

            // don't monopolize processor
            try                 { Thread.sleep(100);   }
            catch (Exception e) { e.printStackTrace(); }
        }
    }

}


Copyright © 2000–2025, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Nov 13 06:00:28 PM EST 2026.