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> {
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> {
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.