luxiaoxun / NettyRpc

A simple RPC framework based on Netty, ZooKeeper and Spring

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

为什么RpcDecoder里面又进行了粘包半包的处理

YANGJINJUE opened this issue · comments

commented
   @Override
    public final void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if (in.readableBytes() < 4) {
            return;
        }
        in.markReaderIndex();
        int dataLength = in.readInt();
        /*if (dataLength <= 0) {
            ctx.close();
        }*/
        if (in.readableBytes() < dataLength) {
            in.resetReaderIndex();
            return;
        }
        byte[] data = new byte[dataLength];
        in.readBytes(data);

        Object obj = SerializationUtil.deserialize(data, genericClass);
        //Object obj = JsonUtil.deserialize(data,genericClass); // Not use this, have some bugs
        out.add(obj);
    }

我看在pipline里面不是已经使用LengthFieldBasedFrameDecoder来解决粘包半包这个问题了吗,这个decode里面直接反序列化是不是就可以了?

先查一下LengthFieldBasedFrameDecoder如何使用,再提问题:
LengthFieldBasedFrameDecoder,在数据包中,加了一个长度字段(长度域),保存上层包的长度。解码的时候,会按照这个长度,进行上层ByteBuf应用包的提取。

commented

int dataLength = in.readInt(); byte[] data = new byte[dataLength]; in.readBytes(data); Object obj = SerializationUtil.deserialize(data, genericClass); out.add(obj);
我的意思是这么多是不是就可以了?

我的代码多了一些检查,更加安全、可靠