1

我使用 ClientBootstrap 在客户端模式下使用 netty。当我大多数时候尝试接收消息时,它工作正常并且只返回一个正文,但有时(服务器总是返回相同的响应)我在内容中得到一个标题,当我调用 message.getContent() 时:

Content-type: text/xml;charset=windows-1251
Content-length: 649
Connection: keep-alive

<?xml version="1.0" encoding="windows-1251"?>
<response>
  <status>
    <code>0</code>
  </status>
  <detail>

显然它应该只是http请求的正文。当它在正文中返回标头部分时,正文部分本身会被标头的大小切割。

这是我的 PiileniFactory:

public ChannelPipeline getPipeline() throws Exception {
    ChannelPipeline pipeline = pipeline();
    if (isSecure) {
        SSLContext clientContext = SSLContext.getInstance("TLS");
        clientContext.init(null, new TrustManager[]{DUMMY_TRUST_MANAGER}, null);
        SSLEngine engine = clientContext.createSSLEngine();
        engine.setUseClientMode(true);
        pipeline.addLast("ssl", new SslHandler(engine));
    }

    pipeline.addLast("codec", new HttpClientCodec());
    pipeline.addLast("aggregator", new HttpChunkAggregator(1048576));
    pipeline.addLast("timeout", new ReadTimeoutHandler(timer, timeout, TimeUnit.MILLISECONDS));
    pipeline.addLast("handler", ibConnectorHandler);
    return pipeline;
}

这是来自 ibConnectorHandler 的 messageReceived:

public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    logger.info("Received");

    HttpResponse response = (HttpResponse) e.getMessage();
    ChannelBuffer resContent = response.getContent();
    byte[] content = null;
    if (resContent.readable()) {
        content = Arrays.copyOf(resContent.array(), resContent.readableBytes());
        logger.debug(Arrays.toString(req.getParams().toArray()) + "----------" + new String(content));
    }

}

我正在使用netty 3.5.8。

UPD 当一切都正确时,resContent 是 org.jboss.netty.buffer.BigEndianHeapChannelBuffer 的 instanceof。当它显示头 resContent 是 org.jboss.netty.buffer.SlicedChannelBuffer 时。所以当netty使用org.jboss.netty.buffer.SlicedChannelBuffer作为http消息的内容时就会出现问题。

4

1 回答 1

2

在“Arrays.copyOf(resContent.array(), resContent.readableBytes())”中,您不尊重数组中的偏移量。您还需要提交可以从 ChannelBuffer.arrayOffset() + ChannelBuffer.readerIndex(); 获得的偏移量;

见:http ://static.netty.io/3.5/api/org/jboss/netty/buffer/ChannelBuffer.html#arrayOffset ()

于 2012-10-10T15:27:31.327 回答