001    
002    /*
003     * Copyright (C) 2011 Archie L. Cobbs. All rights reserved.
004     *
005     * $Id: SocketHandler.java 198 2011-12-30 17:42:55Z archie.cobbs $
006     */
007    
008    package org.dellroad.stuff.net;
009    
010    import java.io.IOException;
011    import java.net.Socket;
012    
013    /**
014     * Implemented by objects that handle individual connections accepted by a {@link SocketAcceptor}.
015     */
016    public interface SocketHandler {
017    
018        /**
019         * Handle the connection.
020         *
021         * @param socket connection socket
022         * @throws IOException if needed
023         */
024        void handleConnection(Socket socket) throws IOException;
025    
026        /**
027         * Receive notification that the server is shutting down.
028         * This method should ensure that the thread currently executing {@link #handleConnection handleConnection()}
029         * returns as soon as possible.
030         *
031         * <p>
032         * After this method returns, the {@code socket} will be closed (if not already). So one way to implement this method
033         * is to simply do nothing, which will trigger an {@link IOException} on the next access from within
034         * {@link #handleConnection handleConnection()}.
035         *
036         * <p>
037         * Alternately, set some flag that {@link #handleConnection handleConnection()} detects each time around its processing loop,
038         * or use {@link Thread#interrupt}, etc.
039         *
040         * <p>
041         * In any case, it is important that {@link #handleConnection handleConnection()} thread does eventually return,
042         * otherwise the thread invoking {@link SocketAcceptor#stop SocketAcceptor.stop()} will hang.
043         *
044         * <p>
045         * Note: it may be that {@link #handleConnection handleConnection()} has already returned when this method is invoked,
046         * in which case this method should do nothing.
047         *
048         * <p>
049         *
050         * @param thread the thread invoking {@link #handleConnection handleConnection()}
051         * @param socket connection socket
052         */
053        void stop(Thread thread, Socket socket);
054    }
055