在netty中添加自带的SslHandler就能支持HTTPS,但是添加之后使用HTTP访问是存在问题的。请问如何能支持使用用一个端口两种协议并行,比如在某个事件中判断出使用HTTPS协议然后在把SslHandler添加到pipeline中。SelfSignedCertificatessc=newSelfSignedCertificate();SslContextsslCtx=SslContextBuilder.forServer(ssc.certificate(),ssc.privateKey()).build();SSLEnginesslEngine=sslCtx.newEngine(UnpooledByteBufAllocator.DEFAULT);ch.pipeline().addFirst(newSslHandler(sslEngine));
2 回答

智慧大石
TA贡献1946条经验 获得超3个赞
根据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());}});
添加回答
举报
0/150
提交
取消