根據(jù)node如何讓一個端口同時支持https與http文中描述的https數(shù)據(jù)流的第一位是十六進制“16”,轉(zhuǎn)換成十進制就是22,在讀取的第一位數(shù)據(jù)進行判斷實現(xiàn)動態(tài)添加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());}});