package com.bonus.tcp.server.config;


import com.bonus.tcp.server.handle.BootNettyChannelInboundHandlerAdapter;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

/**
 * 通道初始化
 * 蚂蚁舞
 */
@ChannelHandler.Sharable//共享的
public class BootNettyChannelInitializer<SocketChannel> extends ChannelInitializer<Channel> {

    //注意超时时间，这里配置，最好设置长点，要不代码 会自动关连接。这里是60秒
    public static long READ_TIME_OUT = 60;

    public static long WRITE_TIME_OUT = 60;

    public static long ALL_TIME_OUT = 60;

    @Override
    protected void initChannel(Channel ch) throws Exception {

        ch.pipeline().addLast(new IdleStateHandler(READ_TIME_OUT, WRITE_TIME_OUT, ALL_TIME_OUT, TimeUnit.SECONDS));

        // 带编码
        ch.pipeline().addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));
        ch.pipeline().addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));

//		// ChannelOutboundHandler，依照逆序执行
//        ch.pipeline().addLast("encoder", new StringEncoder());
//
//        // 属于ChannelInboundHandler，依照顺序执行
//        ch.pipeline().addLast("decoder", new StringDecoder());

        //自定义ChannelInboundHandlerAdapter
        ch.pipeline().addLast(new BootNettyChannelInboundHandlerAdapter());

    }

}
