// 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.netty;

import java.io.UnsupportedEncodingException;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class AsyncServer {
    public static enum NextPhase { WAIT_INTADD, WAIT_STRDUP, DONE }
    private static class ReadHandler extends ChannelInboundHandlerAdapter {
        private ByteBuf inbb;
        private NextPhase state;
        public ReadHandler(Channel ch) {
            inbb = ch.alloc().buffer();
            state = NextPhase.WAIT_INTADD;
        }
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws UnsupportedEncodingException, InterruptedException {
            // append bytes read read from socket to buffer
            inbb.writeBytes((ByteBuf)msg);
            // act based on current state
            switch(state) {
                case WAIT_INTADD:
                    // test if received a and b
                    if(inbb.readableBytes() >= 8) {
                        // read a and b
                        int a = inbb.getInt(0);
                        int b = inbb.getInt(4);
                        // calculate c and send
                        int c = a + b;
                        ByteBuf outbb = ctx.channel().alloc().buffer();
                        outbb.writeInt(c);
                        ctx.channel().writeAndFlush(outbb);
                        // update state
                        state = NextPhase.WAIT_STRDUP;
                    }
                    break;
                case WAIT_STRDUP:
                    // test if received buflen
                    if(inbb.readableBytes() >= 9) {
                        // read v
                        int buflen = inbb.getByte(8);
                        if(inbb.readableBytes() < 9 + buflen) return; // test if received buf
                        byte[] buf = new byte[buflen];
                        inbb.getBytes(9, buf, 0, buflen);
                        String v = new String(buf, "UTF-8");
                        // calculate v2 and send
                        String v2 = v + v;
                        ByteBuf outbb = ctx.channel().alloc().buffer();
                        outbb.writeByte(v2.length());
                        outbb.writeBytes(v2.getBytes("UTF-8"));
                        ctx.channel().writeAndFlush(outbb);
                        // update state
                        state = NextPhase.DONE;
                    }
                    break;
                case DONE:
                    // ignore
                    break;
            }
        }
    }
    private static final int PORT = 12345;
    private static final int BACKLOG = 100;
    public static void main(String[] args) throws InterruptedException {
        // setup context
        EventLoopGroup g = new NioEventLoopGroup(1);
        try {
            ServerBootstrap b = new ServerBootstrap();
            b.group(g).channel(NioServerSocketChannel.class).option(ChannelOption.SO_BACKLOG, BACKLOG);
            // define handler
            b.childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     System.out.printf("(connection from %s)\n", ch.remoteAddress());
                     ch.pipeline().addLast(new ReadHandler(ch));
                 }
             });
            // listen on port
            ChannelFuture f = b.bind(PORT).sync();
            // close connection when done (never)
            f.channel().closeFuture().sync();
        } finally {
            // teardown context
            g.shutdownGracefully();
        }       
    }
}
