ConnectionListener.java


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


/******************************************************************************
 *  Compilation:  javac ConnectionListener.java
 *  Dependencies: Connection.java
 *
 ******************************************************************************/

import java.util.Vector;

public class ConnectionListener extends Thread {
    private Vector<Connection> connections;

    public ConnectionListener(Vector<Connection> connections) {
        this.connections = connections;
    }

    // check for incoming messages and broadcast
    public void run() {
        while (true) {
            for (int i = 0; i < connections.size(); i++) {
                Connection 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 (Connection jth : connections)
                        jth.println(message);

            }

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

}


Copyright © 2000–2017, Robert Sedgewick and Kevin Wayne.
Last updated: Fri Oct 20 14:12:12 EDT 2017.