HttpChannelInitService.java 1.9 KB
package com.zhonglai.socket.html.http;

import com.zhonglai.socket.html.http.handler.HttpServerInboundHandler;
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.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

import javax.net.ssl.SSLEngine;

public class HttpChannelInitService extends ChannelInitializer<SocketChannel> {

    private HttpServerInboundHandler httpServerInboundHandler = null;

    private SslContext sslContext = null;

    public HttpChannelInitService(HttpServerInboundHandler httpServerInboundHandler)
    {
        this.httpServerInboundHandler = httpServerInboundHandler;
    }

    public HttpChannelInitService(HttpServerInboundHandler httpServerInboundHandler, SslContext sslContext)
    {
        this.sslContext = sslContext;
        this.httpServerInboundHandler = httpServerInboundHandler;
    }

    protected void initChannel(SocketChannel ch) throws Exception {

        ChannelPipeline pipeline = ch.pipeline();

        if(null != sslContext)  //https
        {
            SSLEngine engine = sslContext.newEngine(ch.alloc());
            pipeline.addFirst("ssl", new SslHandler(engine));
        }


        pipeline.addLast("http-decoder",
                new HttpRequestDecoder());
        pipeline.addLast("http-aggregator",
                new HttpObjectAggregator(65536));
        pipeline.addLast("http-encoder",
                new HttpResponseEncoder());
        pipeline.addLast("http-chunked",
                new ChunkedWriteHandler());
        pipeline.addLast("httpServerHandler",httpServerInboundHandler
                );

    }
}