我正在使用Netty 5.0,而且它的http功能还是新手。 我需要通过json字符串在Netty服务器和JavaScript应用程序之间进行通信。
服务器处理程序非常简单,如下面的代码:
public class HttpServerHandler extends SimpleChannelInboundHandler<Object> {
@Override
protected void messageReceived(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
}
}
初始化代码:
public class NettyHttpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(8192, Delimiters.lineDelimiter()));
pipeline.addLast("decoder", new StringDecoder(Charset.forName("UTF-8")));
pipeline.addLast("encoder", new StringEncoder(Charset.forName("UTF-8")));
pipeline.addLast("handler", new HttpServerHandler());
}
}
每当客户端通过post方法发送json字符串时,服务器就打印出:
POST / HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Content-Length: 51
Origin: http://127.0.0.1:8888
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/47.0.2526.111 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: */ *
Referer: http://127.0.0.1:8888/MyWebApp02.html
Accept-Encoding: gzip, deflate
Accept-Language: en-US,en;q=0.8
{"cmd":"he", "ver":1, "dvt":3}
我需要的只是最后一行,即json字符串。但是,服务器接收输入为多字符串,我无法将它们转换为高结构(例如HttpRequest
)以获取该内容。我可以解析/检查所有字符串以检测json字符串,但看起来喜欢这是最糟糕的方式。我试图改进代码(例如使用SimpleChannelInboundHandler<FullHttpRequest>
,删除DelimiterBasedFrameDecoder
)但到目前为止没有运气。
答案 0 :(得分:4)
要制作网络服务器,您应该将HttpServerCodec
与HttpObjectAggregator
选项结合使用。
您的ChannelInitializer
应如下所示:
public class NettyHttpServerInitializer extends ChannelInitializer<SocketChannel> {
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline pipeline = ch.pipeline();
pipeline.addLast("http", new HttpServerCodec());
// optional, makes life easier
pipeline.addLast("dechunker", new HttpObjectAggregator(65536));
pipeline.addLast("handler", new HttpServerHandler());
}
}
如果FullHttpRequest
存在,您的处理程序将会处理HttpObjectAggregator
或不同类型的HttpRequest
消息(这更难,请参阅this示例)。
我的回答主要集中在我们收到FullHttpRequest
。
收到FullHttpRequest
后,我们可以做一些事情:
request.getUri()
request.getMethod()
request.headers()
request.content()
要回答您的问题,您应首先致电request.getMethod()
以检查方法是POST还是PUT,然后致电request.content()
以获取内容。
示例:
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
@Override
protected void messageReceived(ChannelHandlerContext ctx, FullHttpRequest msg) throws Exception {
if(msg.getMethod().equals(HttpMethod.POST) || msg.getMethod().equals(HttpMethod.PUT)) {
System.out.println(msg.content().toString(Charset.forName("UTF-8")));
}
}
}