package SimpleChatOne;

// Fri Oct 15 18:07:43 EST 2004
//
// Written by Sean R. Owens, sean at guild dot net, released to the
// public domain.  Share and enjoy.  Since some people argue that it is
// impossible to release software to the public domain, you are also free
// to use this code under any version of the GPL, LPGL, or BSD licenses,
// or contact me for use of another license.
// http://darksleep.com/player

import java.net.Socket;
import java.net.ServerSocket;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;

public class Server {
    private int serverPort = 0;
    private ServerSocket serverSock = null;
    private Socket sock = null;
    private String messageOfTheDay = null;
    private Switchboard switchboard = null;

    public Server(int serverPort, String messageOfTheDay) throws IOException {
	this.serverPort = serverPort;
	this.messageOfTheDay = messageOfTheDay;
	switchboard = new Switchboard();
	serverSock = new ServerSocket(serverPort);
    }
    
    public void waitForConnections() {
	while (true) {
	    try {
		sock = serverSock.accept();
		System.err.println(this.getClass().getName()+":Accepted new socket, creating new handler for it.");

		// Note the order of the next four lines of code.  The
		// order is very important to avoid intermittent, hard
		// to reproduce synchronization errors.  The handler
		// has a reference to switchboard.  It will use
		// switchboard to forward data from it's socket to the
		// other handlers.  The handler will also remove
		// itself from switchboard when its handler closes.
		// If we start handler before it is added to
		// switchboard, there is a chance that the handler's
		// socket will close before the switchboard.add() line
		// is reached, and the handler will try to remove
		// itself from switchboard, which will fail because it
		// is not yet IN switchboard.
		Handler handler = new Handler(sock, switchboard, messageOfTheDay);
		switchboard.add(handler);
		handler.start();
		System.err.println(this.getClass().getName()+":Finished with socket, waiting for next connection.");
	    }
	    catch (IOException e){
		e.printStackTrace(System.err);
	    }
	}
    }

    public static void main(String argv[]) {
	int port = 54321;
	String messageOfTheDay = "Welcome to the SimpleChatOne server.\n";

	Server server = null;
	try {
	    server = new Server(port, messageOfTheDay);
 	}
 	catch (IOException e){
	    e.printStackTrace(System.err);
 	}
	server.waitForConnections();
    }
}

