package com.m2pool.lease.netty.server;


import com.m2pool.lease.netty.handler.MessageToJsonDecoder;
import com.m2pool.lease.netty.handler.MessageToJsonEncoder;
import com.m2pool.lease.netty.handler.ServerChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.timeout.IdleStateHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

import static com.m2pool.lease.netty.message.MethodConstant.PING_TIME;
import static com.m2pool.lease.netty.message.MethodConstant.PONG_TIME;


@Component
public class ServerChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    ServerChannelHandler serverChannelHandler;

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline pipeline = socketChannel.pipeline();
        //IdleStateHandler心跳机制,如果超时触发Handle中userEventTrigger()方法
        pipeline.addLast("idleStateHandler",
                new IdleStateHandler(PONG_TIME, PING_TIME, 0, TimeUnit.SECONDS));
        pipeline.addLast(new LineBasedFrameDecoder(1024));
        //字符串编解码器
        pipeline.addLast(new MessageToJsonDecoder(),new MessageToJsonEncoder());
        //自定义Handler
        pipeline.addLast("serverChannelHandler", serverChannelHandler);
    }
}
