阅读目录
@Override protected void initChannel(Channel ch) throws Exception { ByteBufAllocator byteBufAllocator = ch.alloc(); //对于每个 SslHandler 实例,都使用 Channel 的 ByteBufAllocator 从 SslContext 获取一个新的 SSLEngine SSLEngine sslEngine = context.newEngine(byteBufAllocator); //服务器端模式,客户端模式设置为true sslEngine.setUseClientMode(false); //不需要验证客户端,客户端不设置该项 sslEngine.setNeedClientAuth(false); //要将 SslHandler 设置为第一个 ChannelHandler。这确保了只有在所有其他的 ChannelHandler 将他们的逻辑应用到数据之后,才会进行加密。 //startTls 如果为true,第一个写入的消息将不会被加密(客户端应该设置为true) ch.pipeline().addFirst("ssl",new SslHandler(sslEngine, startTls)); }
tips:对于 ChannelPipeline 链中 ChannelHandler 执行的顺序 —— 入站事件顺序执行、出站事件逆序执行。

Netty 对 HTTP 协议的支持主要提供了以下 ChannelHandler:
HttpResponseDecoder:解码器,用于客户端,解码来自服务端的响应。
HttpRequestEncoder:编码器,用户客户端,编码向服务端发送的请求。
HttpRequestDecoder:解码器,用于服务端,解码来自客户端的请求。
HttpResponseEncoder:编码器,用于服务端,编码向客户端的响应。
HttpClientCodec:编解码器,用户客户端,效果等于 HttpResponseDecoder + HttpRequestEncoder。
HttpServerCodec:编解码器,用户服务端,效果等于 HttpRequestDecoder + HttpResponseEncoder。
HttpObjectAggregator:聚合器,由于 HTTP 的请求和响应可能由许多部分组成,需要聚合它们以形成完整的消息,HttpObjectAggregator 可以将多个消息部分合并为 FullHttpRequest 或者 FullHttpResponse 消息。
HttpContentCompressor:压缩,用户服务端,压缩要传输的数据,支持 gzip 和 deflate 压缩格式。
HttpContentDecompressor:解压缩,用于客户端,解压缩服务端传输的数据。@Override protected void initChannel(Channel ch) throws Exception { ChannelPipeline pipeline = ch.pipeline(); SSLEngine sslEngine = sslContext.newEngine(ch.alloc()); if (isClient) { //使用 HTTPS,添加 SSL 认证 pipeline.addFirst("ssl", new SslHandler(sslEngine, true)); pipeline.addLast("codec", new HttpClientCodec()); //1、建议开启压缩功能以尽可能多地减少传输数据的大小 //2、客户端处理来自服务器的压缩内容 pipeline.addLast("decompressor", new HttpContentDecompressor()); }else { pipeline.addFirst("ssl", new SslHandler(sslEngine)); //HttpServerCodec:将HTTP客户端请求转成HttpRequest对象,将HttpResponse对象编码成HTTP响应发送给客户端。 pipeline.addLast("codec",
关键字:
青岛软件培训
可能你正在寻找一家靠谱的IT培训机构,
渴望突破职业瓶颈,
找一份得体的工作。
恰巧万码学堂正在寻找像你这样不甘平凡的追光者!
我们拒绝纸上谈兵,直接参与真实开发流程!
现在行动,未来可期
立即拨打0532-85025005,预约免费职业规划咨询
前20名咨询者赠送《2025高薪技术岗位白皮书》!
你不是在报名课程,而是在投资五年后的自己!

