package test.recycledChannel;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.net.Socket;
import java.io.IOException;
import java.util.logging.Level;

import com.sun.grizzly.Controller;
import com.sun.grizzly.SelectorHandler;
import com.sun.grizzly.TCPSelectorHandler;
import com.sun.grizzly.utils.ControllerUtils;

/**
 * @author Bongjae Chang
 * @date 2009. 6. 15
 */
public class TimeWaitTest {

    private static final int PORT = 9090;
    private static final int SLEEP_TIME = 3000; // ms

    private final InetAddress localInetAddress;

    private TimeWaitTest() throws UnknownHostException {
        localInetAddress = InetAddress.getLocalHost();
    }

    private void testSimpleConnect() throws IOException {
        final Controller controller = new Controller();
        SelectorHandler selectorHandler = new TCPSelectorHandler();
        ( (TCPSelectorHandler)selectorHandler ).setPort( PORT );
        ( (TCPSelectorHandler)selectorHandler ).setInet( localInetAddress );
        controller.addSelectorHandler( selectorHandler );

        Socket clientSocket = null;
        try {
            ControllerUtils.startController( controller );

            clientSocket = new Socket( localInetAddress, PORT );
            Controller.logger().log( Level.INFO, "Wait for " + SLEEP_TIME + "(ms)" );
            try {
                Thread.sleep( SLEEP_TIME );
            } catch( InterruptedException e ) {
            }

        } finally {
            if( clientSocket != null ) {
                try {
                    clientSocket.shutdownInput();
                } catch( IOException e ) {
                    e.printStackTrace();
                }
                try {
                    clientSocket.shutdownOutput();
                } catch( IOException e ) {
                    e.printStackTrace();
                }
                try {
                    clientSocket.close();
                } catch( IOException e ) {
                    e.printStackTrace();
                }
                clientSocket = null;
            }
            controller.stop();
        }
    }

    public static void main( String[] args ) throws IOException {
        TimeWaitTest test = new TimeWaitTest();
        test.testSimpleConnect();
    }
}