常规netty解码操作如下:
我有点疑惑为什么要用HttpObjectAggregator?
/**
* websocket服务器
*
* @author ling
* @date 2020/1/3
*/
@Component
@Slf4j
public class WebsocketServer implements ApplicationRunner {
@Value("${}")
private Integer port;
@Override
public void run(ApplicationArguments args) {
// 创建主线程池组,处理客户端的连接
NioEventLoopGroup mainGroup = new NioEventLoopGroup();
// 创建从线程池组,处理客户端的读写
NioEventLoopGroup subGroup = new NioEventLoopGroup();
try {
// 创建netty引导类,配置和串联系列组件(设置线程模型,设置通道类型,设置客户端处理器handler,设置绑定端口号)
ServerBootstrap bootstrap = new ServerBootstrap();
(mainGroup, subGroup);
();
(new ChannelInitializer() {
@Override
protected void initChannel(Channel channel) throws Exception {
// 配置链式解码器
ChannelPipeline pipeline = ();
// 解码成HttpRequest
(new HttpServerCodec());
// 解码成FullHttpRequest
(new HttpObjectAggregator(1024*10));
// 添加WebSocket解编码
(new WebSocketServerProtocolHandler("/"));
// 添加处自定义的处理器
(new ServerHanlder());
}
});
// 异步绑定端口号,需要阻塞住直到端口号绑定成功
ChannelFuture channelFuture = (port);
();
("websocket服务端启动成功啦!");
} catch (InterruptedException e) {
("{}websocket服务器启动异常", e);
} finally {
//();
//();
}
}
}
简单来说,如果仅把byte解码成HttpRequest的话,解析请求时会丢失一些信息(这个说法很不具体)。
所以我百度了一波,找到了讲得比较清楚的解释:
当我们用POST方式请求服务器的时候,对应的参数信息是保存在message body中的,如果只是单纯的用HttpServerCodec是无法完全的解析Http POST请求的,因为HttpServerCodec只能获取uri中参数,所以需要加上HttpObjectAggregator。
Http的Get,POST
Get请求包括两个部分:
- request line(包括method,request uri,protocol version))
- header
基本样式:
GET /?name=XXG&age=23 HTTP/1.1 -----> request line
------------------------------------------------------------------
Host: 127.0.0.1:8007
Connection: keep-alive
Cache-Control: max-age=0 -----> header
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
POST请求包括三个部分
- request line(包括method,request uri,protocol version))
- header
- message body
基本样式:
GET / HTTP/1.1 -----> request line
------------------------------------------------------------------
Host: 127.0.0.1:8007
Connection: keep-alive
Content-Length: 15
Cache-Control: max-age=0 -----> header
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/71.0.3578.98 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Accept-Encoding: gzip, deflate, br
Accept-Language: zh-CN,zh;q=0.9
------------------------------------------------------------------
name=XXG&age=23 ------>message body
HttpObjectAggregator
从上可以看出,当我们用POST方式请求服务器的时候,对应的参数信息是保存在message body中的,如果只是单纯的用HttpServerCodec是无法完全的解析Http POST请求的,因为HttpServerCodec只能获取uri中参数,所以需要加上HttpObjectAggregator
以上博客摘自:Netty中的HttpObjectAggregator