s4553711
6/19/2016 - 4:41 PM

A netty server example

A netty server example

package com.ck.runner;

import com.ck.server.DiscardServer;

public class NettyServer {
    public static void main(String[] args) throws Exception {
        int port;
        if (args.length > 0) {
            port = Integer.parseInt(args[0]);
        } else {
            port = 9090;
        }
        System.out.println("Server Start "+port);
        new DiscardServer(port).run();
    }
}
package com.ck.server;

import java.util.concurrent.LinkedBlockingQueue;

import com.ck.util.MemQueue;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelPromise;
import io.netty.util.ReferenceCountUtil;

public class DiscardServerHandler extends ChannelInboundHandlerAdapter {
//    private MemQueue mem;
//    private Thread t;
//    
//    public DiscardServerHandler() {
//        super();
//        System.out.println("called once");
//        mem = new MemQueue(new LinkedBlockingQueue<byte[]>());
//        t = new Thread(mem);
//        t.start();
//    }
    
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) {
        ByteBuf in = (ByteBuf) msg;
        try {
            //System.out.println("<read start>");
            System.out.print(in.toString(io.netty.util.CharsetUtil.US_ASCII));
            //while (in.isReadable()) {
            //    System.out.print((char) in.readByte());
            //}
            //System.out.println("<read end>");
        } finally {
            //System.out.flush();
            ReferenceCountUtil.release(msg);
        }
    }
    
    @Override
    public void exceptionCaught(ChannelHandlerContext arg0, Throwable arg1) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void handlerAdded(ChannelHandlerContext arg0) throws Exception {
        // TODO Auto-generated method stub

    }

    @Override
    public void handlerRemoved(ChannelHandlerContext arg0) throws Exception {
        // TODO Auto-generated method stub

    }

}
package com.ck.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.FixedRecvByteBufAllocator;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class DiscardServer {
    private int port;

    public DiscardServer(int port) {
        this.port = port;
    }

    public void run() throws Exception {
        EventLoopGroup bossGroup = new NioEventLoopGroup(); // (1)
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap(); // (2)
            //final DiscardServerHandler handler = new DiscardServerHandler();
            
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class) // (3)
             .childHandler(new ChannelInitializer<SocketChannel>() { // (4)
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     ch.config().setRecvByteBufAllocator(new FixedRecvByteBufAllocator(8*1024*1024));
                     ch.pipeline().addLast(new DiscardServerHandler());
                     //ch.pipeline().addLast(new TimeDecoder(), new DiscardServerHandler());
                     //ch.pipeline().addLast(new SimpleDiscardHandler());              
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)          // (5)
             .childOption(ChannelOption.SO_KEEPALIVE, true); // (6)

            // Bind and start to accept incoming connections.
            ChannelFuture f = b.bind(port).sync(); // (7)

            // Wait until the server socket is closed.
            // In this example, this does not happen, but you can do that to gracefully
            // shut down your server.
            f.channel().closeFuture().sync();
        } finally {
            workerGroup.shutdownGracefully();
            bossGroup.shutdownGracefully();
        }
    }
}