import JConnection;

import java.io.*;
import java.net.*;
import java.util.Vector;


public class JChatServer extends Thread {
    public static final int DEFAULT_PORT = 33333;	// Default-Portnummer
    public static final String DEFAULT_ADDR = "localhost";
    int port;					// aktuelle Portnummer
    ServerSocket server_socket;			// Der Socket des Servers
    Vector connections;				// Vektor aller aktiven Verbindungen
    int num_connections;			

    // Methode zur Ausgabe von Fehlern auf der Kommandozeile
    public static void fail(Exception e, String msg) {
        System.err.println(msg + ": " + e);
        System.exit(1);
    }

    public JChatServer(int port) {
        this.port = port;	// Port initialisieren
        connections = new Vector();
        try {
            server_socket = new ServerSocket(port);
            System.out.println(server_socket +
                "\nServer lauscht auf Port " + port);
        }
        catch(IOException e) {
            fail(e, "Eine Ausnahme trat beim Anlegen des Server Socket auf");
        }
        this.start();
    }

    public void run() {
        try {
            while(true) {
                Socket client_socket = server_socket.accept();
                JConnection c = new JConnection(client_socket, this);
                addConnection(c);
            }
        }
        catch(IOException e) {
            fail(e, "Beim Warten auf Verbindungen ist eine Ausnahme aufgetreten");
        }
    }

    public synchronized void addConnection(JConnection c) {
        connections.addElement(c);
        num_connections++;
    }

    public synchronized void receive(String line, JConnection c) {
        for (int i = 0; i < num_connections; i++) {
            JConnection ci = (JConnection)connections.elementAt(i);
            if ((ci != null) && (ci.isAlive())) ci.send(line);
        }
    }
    
}
