package com.ym.im.core;


import com.ym.im.entity.NettyConstant;
import com.ym.im.handler.IndexHandler;
import com.ym.im.handler.SingleChatHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
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.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

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

    @Autowired
    private SingleChatHandler singleChatHandler;

    @Autowired
    private IndexHandler indexHandler;

    @Autowired
    private MessageEncoder messageEncoder;

    @Autowired
    private MessageDecoder messageDecoder;


    @Override
    protected void initChannel(SocketChannel sc) throws Exception {

        ChannelPipeline pipeline = sc.pipeline();
        //websocket协议本身是基于http协议的，所以要使用http解编码器
        pipeline.addLast(new HttpServerCodec());
        pipeline.addLast(new ChunkedWriteHandler());
        pipeline.addLast(new HttpObjectAggregator(NettyConstant.MAX_FRAME_LENGTH));
        pipeline.addLast(indexHandler);
        pipeline.addLast(new WebSocketServerProtocolHandler(NettyConstant.WS));
        pipeline.addLast(messageDecoder);
        pipeline.addLast(messageEncoder);
        pipeline.addLast(singleChatHandler);

    }
}
