Netty ByteBuf在解码时不会获得大输入的完整消息
有一个遗留应用程序通过TCP执行json。
我使用netty服务器,我想通过Gson将json转换为Pojo。
为了做到这一点,我转换创建了一个Decoder,它将ByteBuf作为输入并创建My Object。
问题是Bytebuf的大小为1024,json比那个大得多(> 20mo)
@Sharable public class RequestDecoder extends MessageToMessageDecoder { @Override protected void decode(ChannelHandlerContext ctx, ByteBuf msg, List 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)
我怎样才能摆脱这种限制?
尝试使用不同的解码器 例如,尝试ReplayingDecoder 。
Netty中有许多解码器。 您必须选择最合适的解码器并根据您的要求实施。
使用ReplayingDecoder时,请确保知道要准确读取的字节数。 通常,要读取的字节大小在网络数据包的开头发送。 这实际上取决于您的服务器+客户端协议实现。
我在管道的开头添加了DelimiterBasedFrameDecoder:
pipeline.addLast("framer", new DelimiterBasedFrameDecoder(Integer.MAX_VALUE, Unpooled.wrappedBuffer(new byte[]{'E', 'O', 'F', '\n'})));
因为我发现所有json都被“EOF \ n”终止(由于遗留问题)
这对我来说没问题,但是当这个遗留问题得到解决时会发生什么?