package com.ym.im.core;


import com.ym.im.entity.base.NettyConstant;
import com.ym.im.handler.SingleChatHandler;
import com.ym.im.handler.WebSocketHandshakerHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.util.concurrent.EventExecutorGroup;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

/**
 * @author: JJww
 * @Date:2019-01-21
 */
@Component
public class WebSocketChannelInitializer extends ChannelInitializer<NioSocketChannel> {

    @Autowired
    private MessageEncoder messageEncoder;

    @Autowired
    private MessageDecoder messageDecoder;

    @Autowired
    @Qualifier("businessGroup")
    private EventExecutorGroup businessGroup;

    @Autowired
    private SingleChatHandler singleChatHandler;

    @Autowired
    private WebSocketHandshakerHandler webSocketHandshakerHandler;


    @Override
    protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
        nioSocketChannel.pipeline()
                .addLast(new HttpServerCodec(),
                        new HttpObjectAggregator(NettyConstant.MAX_FRAME_LENGTH),
                        webSocketHandshakerHandler,
                        new WebSocketServerProtocolHandler(NettyConstant.CS),
                        messageDecoder,
                        messageEncoder)
                .addLast(businessGroup, singleChatHandler);//复杂业务绑定businessGroup
    }
}
