0

我使用以下处理程序在 Netty 中创建了一个 HTTPServer:

public class HttpRouterServerHandler extends SimpleChannelInboundHandler<HttpRequest> {

public void channelRead0(ChannelHandlerContext ctx, HttpRequest req) {
  if (HttpUtil.is100ContinueExpected(req)) {
     ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
     return;
  }

  System.out.println(req.toString());
  HttpResponse res = /* create the response here */      
  flushResponse(ctx, req, res);
}

我使用 http.client 在 Python 中发送 PUT 请求:

     json_data = /* constructJSON content */
     connection = http.client.HTTPConnection("localhost", 8080)
     connection.request("PUT", "/proto/api/send", json_data)     
     response = self.connection.getresponse()
     connection.close()

由于某种原因,我无法获取请求的 BODY(json 内容)。原因似乎是 my HttpRequestis not a FullHttpRequest,所以我无法得到它content()

如果我打印我的请求内容,我有类似的内容:

DefaultHttpRequest(decodeResult: success, version: HTTP/1.1)
PUT /proto/api/send HTTP/1.1
Host: localhost:8080
Accept-Encoding: identity
content-length: 47

此外,我尝试用 FullHttpRequest 替换我的处理程序的 HttpRequest,但在这种情况下,Netty 服务器不再响应,这导致 Python 中出现异常:

public class HttpRouterServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {

  public void channelRead0(ChannelHandlerContext ctx, FullHttpRequest req) {
    if (HttpUtil.is100ContinueExpected(req)) {
       ctx.writeAndFlush(new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.CONTINUE));
    return;
  } 

   System.out.println(req.toString());
   HttpResponse res = /* create the response here */      
   flushResponse(ctx, req, res);
}

我的错误在哪里?

4

2 回答 2

1

如果您不使用FullHttpRequest,您将收到以下消息:

  • 一条HttpRequest消息
  • 零个或多个HttpContent消息
  • 一条LastHttpContent消息

第一个代码片段的问题是它只接受HttpRequest,如果你想获得上述所有消息,你应该接受HttpObject

我不确定第二个片段有什么问题,很可能您没有收到整个内容,因此FullHttpRequest没有创建和发出。我会建议LoggingHandler在管道中添加一个,看看你在网上收到了什么。

于 2021-07-23T17:04:50.820 回答
0

我的错误在初始化程序中。我做了:

public class HttpRouterServerInitializer extends ChannelInitializer<SocketChannel> {
  private final HttpRouterServerHandler handler;

  public HttpRouterServerInitializer(HttpPythonModule module) {
     handler = new HttpRouterServerHandler(moduler);
  }

  public void initChannel(SocketChannel ch) {
     ch.pipeline()
        .addLast(new HttpServerCodec())
        .addLast(handler)
  }
}

我应该做的地方:

public class HttpRouterServerInitializer extends ChannelInitializer<SocketChannel> {
  private final HttpRouterServerHandler handler;

  public HttpRouterServerInitializer(HttpPythonModule module) {
     handler = new HttpRouterServerHandler(moduler);
  }

  public void initChannel(SocketChannel ch) {
     ch.pipeline()
        .addLast(new HttpServerCodec())
        .addLast(new HttpObjectAggregator(Integer.MAX_VALUE))
        .addLast(handler)
  }
}

Netty 文档中提到了这个HttpObjectAggregator类:

ChannelHandler 将 HttpMessage 及其后续 HttpContents 聚合为单个 FullHttpRequest 或 FullHttpResponse(取决于它是否用于处理请求或响应),没有后续 HttpContents。

于 2021-07-27T14:04:50.043 回答