智慧大石
根据node如何让一个端口同时支持https与http文中描述的https数据流的第一位是十六进制“16”,转换成十进制就是22,在读取的第一位数据进行判断实现动态添加ChannelHandler。.childHandler(newChannelInitializer(){protectedvoidinitChannel(finalNioSocketChannelch)throwsException{ch.pipeline().addFirst(newChannelInboundHandlerAdapter(){@OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{if(((ByteBuf)msg).getByte(0)==22){SelfSignedCertificatessc=newSelfSignedCertificate();SslContextsslCtx=SslContextBuilder.forServer(ssc.certificate(),ssc.privateKey()).build();SSLEnginesslEngine=sslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);//将处理https的处理程序添加至HttpServerCodec之前ctx.pipeline().addBefore("HttpServerCodec","sslHandler",newSslHandler(sslEngine));}ctx.pipeline().remove(this);super.channelRead(ctx,msg);}});ch.pipeline().addLast("HttpServerCodec",newHttpServerCodec());ch.pipeline().addLast("aggregator",newHttpObjectAggregator(10*1024*1024));ch.pipeline().addLast(newHttpServerHandler());}});反之先添加sslHandler在移除也行.childHandler(newChannelInitializer(){protectedvoidinitChannel(finalNioSocketChannelch)throwsException{ch.pipeline().addFirst(newChannelInboundHandlerAdapter(){@OverridepublicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{if(((ByteBuf)msg).getByte(0)!=22){//删除sslHandlerctx.pipeline().remove("sslHandler");}ctx.pipeline().remove(this);super.channelRead(ctx,msg);}});SelfSignedCertificatessc=newSelfSignedCertificate();SslContextsslCtx=SslContextBuilder.forServer(ssc.certificate(),ssc.privateKey()).build();SSLEnginesslEngine=sslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);ch.pipeline().addLast("sslHandler",newSslHandler(sslEngine));ch.pipeline().addLast("HttpServerCodec",newHttpServerCodec());ch.pipeline().addLast("aggregator",newHttpObjectAggregator(10*1024*1024));ch.pipeline().addLast(newHttpServerHandler());}});