import java.io.*;
import java.net.*;

public class DialogServer {
    public static void main(String args[]) {

	String hostname;
	try {
	    InetAddress localAddress= InetAddress.getLocalHost();
	    hostname = localAddress.getHostName();
	}
	catch (Exception e) {
	    return;
	}
	System.err.println("Hostname: "+hostname);
	
	// declaration section:
	// declare a server socket and a client socket for the server
	// declare an input and an output stream

	ServerSocket serverSocket = null;
	Socket clientSocket = null;

	// Try to open a server socket on port 9999
	// Note that we can't choose a port less than 1023 if we are not
	// privileged users (root)

	System.err.println("Starting server on host "+hostname+" port 9999 ...");
	try {
	    serverSocket = new ServerSocket(9999);
	}
	catch (IOException e) {
	    System.err.println(e);
	    return;
	}   

	System.err.println("Waiting for connection ...");
	try {
	    // Create a socket object from the ServerSocket to listen and
	    // accept connections.
	    clientSocket = serverSocket.accept();

	    System.err.println("Connection received; starting dialog with client ...");
	    Dialog dialog =
		new Dialog(clientSocket.getInputStream(),
			   clientSocket.getOutputStream());
	    dialog.run();
	    System.err.println("End of connection");
	}   
	catch (IOException e) {
	    System.err.println(e);
	    return;
	}
    }
}
