package com.xueyi.nlt.netty.client.codec;

import com.xueyi.nlt.netty.client.handler.MockClientHandler;
import com.xueyi.nlt.netty.client.handler.NettyClientHandler;
import com.xueyi.nlt.netty.client.handler.WsClientHandler;
import io.netty.channel.Channel;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.handler.codec.http.HttpClientCodec;
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.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

public class WsChannelInitializer extends ChannelInitializer {

    private NettyClientHandler nettyClientHandler;

    public WsChannelInitializer(NettyClientHandler nettyClientHandler) {
        this.nettyClientHandler = nettyClientHandler;
    }

    @Override
    protected void initChannel(Channel ch) {
        ChannelPipeline pipeline = ch.pipeline();
        // websocket是基于http协议的，所以需要使用http编解码器
        pipeline.addLast(new HttpClientCodec());
        pipeline.addLast(new LoggingHandler(LogLevel.INFO));
        pipeline.addLast("decoder", new StringDecoder());
        pipeline.addLast("encoder", new StringEncoder());
        // 以上三个处理器是对http协议的支持

        // websocket 服务器处理的协议，并用于指定客户端连接的路由(这里指定的是 /ws)
        // 这里的URL就是 ws://ip:port/ws
        // 该处理器为运行websocket服务器承担了所有繁重的工作
        // 它会负责websocket的握手以及处理控制帧
        // websocket的数据传输都是以frames进行的
        pipeline.addLast(new WebSocketServerProtocolHandler("/wss"));
        // 自定义的处理器
        pipeline.addLast("handler", nettyClientHandler);
    }
}
