// Collection of code snippets by Arne Vajhøj 
// (from articles on eksperten.dk / vajhoej.dk written sometime between 2004 and now) 
package socket.plain.binary.modern;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class SelectServer {
    public static interface EventHandler {
        public void process() throws IOException;
    }
    public static class ConnectionHandler implements EventHandler {
        private ServerSocketChannel ssc;
        private Selector sel;
        public ConnectionHandler(ServerSocketChannel ssc, Selector sel) {
            this.ssc = ssc;
            this.sel = sel;
        }
        @Override
        public void process() throws IOException {
            // accept connection
            SocketChannel sc = ssc.accept();
            System.out.printf("(connection from %s)\n", sc.getRemoteAddress());
            sc.configureBlocking(false);
            // register receive integers handler
            sc.register(sel, SelectionKey.OP_READ, new ReceiveIntegersHandler(sc, sel));
        }
    }
    public static class ReceiveIntegersHandler implements EventHandler {
        private SocketChannel sc;
        private Selector sel;
        public ReceiveIntegersHandler(SocketChannel sc, Selector sel) {
            this.sc = sc;
            this.sel = sel;
        }
        @Override
        public void process() throws IOException {
            ByteBuffer bb;
            // read a and b
            bb = ByteBuffer.allocate(8);
            while(bb.hasRemaining() && sc.read(bb) >= 0);
            bb.rewind();
            bb.order(ByteOrder.BIG_ENDIAN);
            int a = bb.getInt();
            int b = bb.getInt();
            // calculate c and send
            int c = a + b;
            bb = ByteBuffer.allocate(4);
            bb.order(ByteOrder.BIG_ENDIAN);
            bb.putInt(c);
            bb.rewind();
            sc.write(bb);
            // register receive string handler
            sc.register(sel, SelectionKey.OP_READ, new ReceiveStringHandler(sc));
        }
    }
    public static class ReceiveStringHandler implements EventHandler {
        private SocketChannel sc;
        public ReceiveStringHandler(SocketChannel sc) {
            this.sc = sc;
        }
        @Override
        public void process() throws IOException {
            ByteBuffer bb;
            // read v
            bb = ByteBuffer.allocate(1);
            while(bb.hasRemaining() && sc.read(bb) >= 0);
            bb.rewind();
            int buflen = bb.get();
            bb = ByteBuffer.allocate(buflen);
            while(bb.hasRemaining() && sc.read(bb) >= 0);
            bb.rewind();
            byte[] buf = new byte[buflen];
            bb.get(buf);
            String v = new String(buf, "UTF-8");
            // calculate v2 and send
            String v2 = v + v;
            byte[] v2b = v2.getBytes("UTF-8");
            bb = ByteBuffer.allocate(1 + v2b.length);
            bb.put((byte)v2b.length);
            bb.put(v2b);
            bb.rewind();
            sc.write(bb);
            // close connection
            sc.close();
        }
    }
    private static final int PORT = 12345;
    public static void main(String[] args) {
        try {
            // selector initiating all events
            Selector sel = Selector.open();
            // listen on port
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(PORT));
            ssc.configureBlocking(false);
            // register connection handler
            ssc.register(sel, SelectionKey.OP_ACCEPT, new ConnectionHandler(ssc, sel));
            while(true) {
                sel.select();
                Iterator<SelectionKey> it = sel.selectedKeys().iterator();
                while(it.hasNext()) {
                    SelectionKey sk = it.next();
                    EventHandler eh = (EventHandler) sk.attachment();
                    eh.process();
                    it.remove();
                }
            }
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }
}
