package com.sv.netty.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import io.netty.handler.timeout.ReadTimeoutHandler;
import org.springframework.stereotype.Component;

import java.nio.charset.Charset;

/**
 * 服务器端协议初始化适配器
 *
 * @Author peakren
 * @Date 09/05/2017 5:19 PM
 */
@Component
public class ServerProtocolInitalizer extends ChannelInitializer<SocketChannel> {

    private ChannelHandler handler;
    private final int IDLE_TIME = 15;  //连接检测空闲时间
    private final int READ_TIME = 15; //读超时时间
    private final int WRITE_TIME = 15; //写超时时间
    private final int READ_TIMEOUT = 300; //读超时时间

    @Override
    protected void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addFirst(new LengthFieldBasedFrameDecoder(Integer.MAX_VALUE, 4, 4, 0, 0));
        pipeline.addLast(new IdleStateHandler(IDLE_TIME, READ_TIME, WRITE_TIME));
        pipeline.addLast(new ReadTimeoutHandler(READ_TIMEOUT));
        pipeline.addLast(new MessageDecoder());
        pipeline.addLast(new MessageEncoder());
        pipeline.addLast(new ServerHandler());

    }

    public ChannelHandler getHandler() {
        return handler;
    }

    public void setHandler(ChannelHandler handler) {
        this.handler = handler;
    }

}
