Netty 支持 HTTP 协议

本文介绍了如何利用Netty框架支持HTTP协议,包括服务端和客户端的实践示例,展示了Netty处理HttpRequest和HttpResponse的能力。
摘要由CSDN通过智能技术生成

 Netty 支持 HTTP 协议


对于 HTTP/HTTPS 协议的支持,Netty 提供以下的 codec 编解码器支持:
HttpRequestEncoder 对 HTTP 请求进行解码,用于服务端入站
HttpResponseEncoder 对 HTTP 响应进行解码,用于客户端入站
HttpRequestDecoder 对 HTTP 请求进行编码,用于客户端出站
HttpResponseDecoder 对 HTTP 响应进行编码,用于服务端出站

Netty 使用 FullHttpRequest、FullHttpResponse 分别表示一个 HTTP请求,HTTP响应,它们的各自的组成结构如下:

① HttpRequest:请求头信息对象;
② HttpContent:请求正文对象,一个 FullHttpRequest 中可以包含多个 HttpContent;
③ LastHttpContent:标记请求正文的结束,可能会包含请求头的尾部信息;

① HttpResponse:响应头信息对象;
② HttpContent:响应正文对象,一个 FullHttpResponse 中可以包含多个 HttpContent;
③ LastHttpContent:标记响应正文的结束,可能会包含响应头的尾部信息;

如果使得 Netty 客户端、服务端支持 HTTP ,只需要添加相应的 Http codc 即可,十分简便,如下:
服务端支持 HTTP
 
public class HttpPipelineInitializer extends ChannelInitializer<Channel> {
           
    @Override
    protected void initChannel(Channel ch) throws Exception {
           
        ChannelPipeline pipeline = ch.pipeline();
         pipeline.addLast("decoder", new HttpRequestDecoder());   //Http请求入站解码
         pipeline.addLast("encoder", new HttpResponseEncoder());   //Http响应出站编码
    }
}
客户端支持 HTTP
 
public class HttpPipelineInitializer extends ChannelInitializer<Channel> {
           
    @Override
    protected void initChannel(Channel ch) throws Exception {
           
        ChannelPipeline pipeline = ch.pipeline();
        pipeline.addLast("decoder", new HttpResponseDecoder());  //Http响应入站解码
        pipeline.addLast("encoder", new HttpRequestEncoder());  //Http请求出站编码
    }
}

实践示例

以下通过一个例子来说明 Netty 客户端、服务端支持 HTTP 的用法,完整示例地址: https://gitee.com/assad/netty-test-sample/tree/master/netty-test-sample/src/main/java/httpSample

业务逻辑为:HttpClient 向 HttpServer 发送请求,HttpSever 获取请求,回传一个包含请求正文的响应给 HttpClient;

服务端

服务端引导类:HttpServer
 
public class HttpServer {
           
    private final int port;
    public HttpServer(int port) {
           
        this.port = port;
    }
    public void start() throws InterruptedException {
           
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try{
           
            ServerBootstrap bootstrap = new ServerBootstrap();
             bootstrap.group(bossGroup,workerGroup)
                     .channel(NioServerSocketChannel.
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值