为了账号安全,请及时绑定邮箱和手机立即绑定

有没有童鞋遇到过同样的问题: netty怎么才能 同时支持HTTP与HTTPS

有没有童鞋遇到过同样的问题: netty怎么才能 同时支持HTTP与HTTPS

德玛西亚99 2019-06-13 09:56:24
在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(){
@Override
publicvoidchannelRead(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(){
@Override
publicvoidchannelRead(ChannelHandlerContextctx,Objectmsg)throwsException{
if(((ByteBuf)msg).getByte(0)!=22){
//删除sslHandler
ctx.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());
}
});
                            
查看完整回答
反对 回复 2019-06-13
  • 2 回答
  • 0 关注
  • 479 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号