Server.java 2.0 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48
package com.kwan.shuyu.netty;

import com.kwan.shuyu.netty.handler.IProtocalHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.DefaultEventExecutorGroup;

public class Server {
    private static void start(int port) throws InterruptedException {
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            ServerBootstrap b = new ServerBootstrap();//Bootstrap for client
            b.group(bossGroup, workerGroup);
            b.channel(NioServerSocketChannel.class);//always
            b.childHandler(new ChannelInitializer() {
                @Override
                protected void initChannel(Channel ch) throws Exception {
                    //ch.pipeline().addLast(new PrintInboundHandler("id1"));
//					 ch.pipeline().addLast(new LineBasedFrameDecoder(80,false,false));
//					 ch.pipeline().addLast(new StringDecoder());
//					 ch.pipeline().addLast(new EchoHandler());
                    ch.pipeline().addLast(new LengthFieldBasedFrameDecoder(1024, 2, 2, -2, 0));
                    ch.pipeline().addLast(new DefaultEventExecutorGroup(16), new IProtocalHandler());

                    ch.pipeline().addLast(new StringEncoder(CharsetUtil.UTF_8));
                }
            });
            ChannelFuture f = b.bind(port).sync();
            f.channel().closeFuture().sync();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }

    public static void main(String[] args) throws InterruptedException {
        start(8084);
    }
}