使用类EmbeddedChannel测试编解码器:调用writeOutbound()方法,然后调用readOutbound()

时间:2019-04-11 08:23:36

标签: java netty

当我使用类EmbeddedChannelLengthFieldBasedFrameDecoder的自定义协议中测试LengthFieldPrependerProtoBuf的正确性时,我希望通过编码来获取所有数据。首先,我调用方法ch.writeOutbound()添加我的消息对象。其次,我调用方法ch.readOutbound()来获取ByteBuf。我期望得到结合长度字段ByteBuf和消息ByteBuf的ByteBuf。但是我只得到ByteBuf来包装PooledUnsafeDirectByteBuf(ridx: 0, widx: 4, cap: 4)的长度字段。这让我感到困惑。然后我调试程序。我可以了解从outmessage进行轮询的原理。所以我首先得到长度字段ByteBuf。为什么以这种方式设计?我可以通过编码获取所有数据吗?以下是我的测试代码。

@test
public void testAlarmProto(){

    AlarmProto.Alarm.Builder builder = AlarmProto.Alarm.newBuilder();

    builder.setCommunity("Quene Home");
    builder.setBuildingId(31);
    builder.setBuildingPart("B");
    builder.setCellId(1);
    builder.setRoomId(204);
    builder.setAlarmCategory("Fire");
    builder.setAttachment("Current time");

    MessageProto.MessageBase.Body.Builder body = MessageProto.MessageBase.Body.newBuilder();
    body.setContext(builder.build());

    MessageProto.MessageBase.Header.Builder header =MessageProto.MessageBase.Header.newBuilder();
    header.setType(MessageProto.MessageBase.MessageType.SERVICE_REQ);

    MessageProto.MessageBase.Builder message = MessageProto.MessageBase.newBuilder();
    message.setHeader(header.build());
    message.setBody(body.build());

   //create EmbeddedChannel
    EmbeddedChannel ch = new EmbeddedChannel();

    ch.pipeline().addLast("frameDecoder",new LengthFieldBasedFrameDecoder(1048576,0,4,0,4));
   // ch.pipeline().addLast("frameDecoder",new ProtobufVarint32FrameDecoder());
    ch.pipeline().addLast("decoder",new ProtobufDecoder(MessageProto.MessageBase.getDefaultInstance()));
    ch.pipeline().addLast("frameEncoder",new LengthFieldPrepender(4));

  //  ch.pipeline().addLast("frameEncoder",new ProtobufVarint32LengthFieldPrepender());
    ch.pipeline().addLast("encoder",new ProtobufEncoder());

   //write outbound data to ch
    ch.writeOutbound(message.build());

   //get data from ch but only the 
    ByteBuf byteBuf = ch.readOutbound();

    ch.writeInbound(byteBuf);
    ch.finish();
    MessageProto.MessageBase messageBase = ch.readInbound();

    System.out.println(messageBase.getHeader().getType().getNumber());
    System.out.println(messageBase.getBody().getContext().getBuildingPart());

}

0 个答案:

没有答案