// 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.ServerSocketChannel;
import java.nio.channels.SocketChannel;

public class MultiServer {
    public static class ClientHandler extends Thread {
        private SocketChannel sc;
        public ClientHandler(SocketChannel sc) {
            this.sc = sc;
        }
        @Override
        public void run() {
            try {
                System.out.printf("(handler in thread %d)\n", Thread.currentThread().getId());
                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);
                // read v
                bb = ByteBuffer.allocate(1);
                sc.read(bb);
                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();
            } catch (IOException e) {
                // TODO
                e.printStackTrace();
            }
        }
    }
    private static final int PORT = 12345;
    public static void main(String[] args) {
        try {
            // listen on port
            ServerSocketChannel ssc = ServerSocketChannel.open();
            ssc.bind(new InetSocketAddress(PORT));
            while(true) {
                // accept connection
                SocketChannel sc = ssc.accept();
                System.out.printf("(connection from %s)\n", sc.getRemoteAddress());
                // start new thread to handle connection
                (new ClientHandler(sc)).start();
            }
        } catch (IOException e) {
            // TODO
            e.printStackTrace();
        }
    }
}
