【问题标题】:Netty ByteBuf dont get the full message of a large input when decodingNetty ByteBuf 在解码时没有得到大输入的完整消息
【发布时间】:2014-04-29 01:56:00
【问题描述】:

有一个遗留应用程序通过 TCP 处理 json。

我用的是netty服务器,我想通过Gson把json转成Pojo。

为了做到这一点,我转换创建了一个解码器,它将一个 ByteBuf 作为输入并创建了我的对象。

问题是 Bytebuf 的大小为 1024,而 json 比这大得多 (>20mo)

@Sharable
public class RequestDecoder extends MessageToMessageDecoder<ByteBuf> {

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception {
        InputStream json = new ByteBufInputStream(msg);
        InputStreamReader inputStreamReader = new InputStreamReader(json, Charsets.UTF_8);
        JsonReader reader;
        reader = new JsonReader(inputStreamReader);
        reader.setLenient(true);
        Request object = new Gson().fromJson(reader, Request.class);
        try {
            reader.close();
        } catch (IOException e) {
            throw new RuntimeException("uncloseable reader", e);
        }
        out.add(object);
    }
}

我总是得到一个:

com.google.gson.stream.MalformedJsonException: Unterminated string at line 1 column 1020

当我调试时,我只得到“ByteBuf msg”中的第 1024 个字节

如何将 ByteBuf 容量设置为其最大容量? (调试时我看到 ByteBuf 是一个 SimpleLeakAwareByteBuf,maxCapacity 为 2147483647)

我怎样才能摆脱这个限制?

【问题讨论】:

    标签: java stream gson netty


    【解决方案1】:

    我在管道的开头添加了一个 DelimiterBasedFrameDecoder :

    pipeline.addLast("framer", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.wrappedBuffer(new byte[]{'E', 'O', 'F', '\n'})));
    

    因为我发现所有 json 都以“EOF\n”终止(由于遗留问题)

    现在对我来说没问题,但是当这个遗留问题解决后会发生什么?

    【讨论】:

      【解决方案2】:

      尝试使用不同的解码器。例如,试试ReplayingDecoder

      Netty 中有许多可用的解码器。您必须选择最合适的解码器并根据您的要求实施。

      使用 ReplayingDecoder 时,请确保知道您想准确读取多少字节。通常,要读取的字节大小在网络数据包的开头发送。这实际上取决于您的服务器 + 客户端协议实现。

      【讨论】:

      • 就是这个问题,不知道发送的数据大小
      猜你喜欢
      • 1970-01-01
      • 2015-09-28
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 2017-11-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多