在我的应用程序中,我需要在套接字上接收一个字节数组,将其解析为 HttpRequest
以执行一些检查,如果检查通过,则返回字节数组并执行更多操作工作。
该应用程序基于 NETTY(这是一个要求)。
我的第一个想法是创建一个像这样的管道:
HttpRequestDecoder
(从ByteBuf
解码为HttpRequest
)MyHttpRequestHandler
(对HttpRequest
进行我自己的检查)HttpRequestEncoder
(将HttpRequest
编码为ByteBuf
)MyButeBufHandler
(使用ByteBuf
进行工作)
但是,HttpRequestEncoder
扩展了 ChannelOutboundHandlerAdapter
,因此不会为入站数据调用它。
我怎样才能完成这个任务? 最好避免对请求进行解码和重新编码。
问候, 马西米利亚诺
最佳答案
在 MyHttpRequestHandler
中使用 EmbeddedChannel
。
EmbeddedChannel ch = new EmbeddedChannel(new HttpRequestEncoder()); ch.writeOutbound(msg); ByteBuf 编码 = ch.readOutbound();
您必须将 EmbeddedChannel
保留为 MyHttpRequestEncoder
的成员变量,因为 HttpRequestEncoder
是有状态的。另外,请在使用完毕后关闭 EmbeddedChannel
(可能在您的 channelInactive()
方法中。)
关于java - Netty 将 HttpRequest 转换为 ByteBuf,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29230268/