Outgoing MessageToByteEncoder is always returning null

Viewed 27

I'm using netty 4.1.77.Final to create a Message encoder. The frames use the following protocol: two bytes as the length of the string and then an ASCII string. When trying to test the encoder with EmbeddedChannel I always get a null outbound result! I see my code getting executed but the result is always null!

Here is the encoder:

public class MessageOutboundEncoder extends MessageToByteEncoder<String> {
@Override
    protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
        byteBuf.writeShort(s.length());
        byteBuf.writeBytes(s.getBytes());
    }
}

Here is the test which always fails:

@Test
public void encode03 () {
    EmbeddedChannel channel = new EmbeddedChannel(new MessageOutboundEncoder());
    String s = "Howdy";
    channel.writeOneOutbound(s);
    ByteBuf byteBuf = channel.readOutbound();
    assert(byteBuf != null);
}

Any help would be appreciated!

1 Answers

It turns out that the solution is to use writeAndFlush in the encoder rather than just writing to the byte buf, so the correct code for the encoder is

@Override
protected void encode(ChannelHandlerContext channelHandlerContext, String s, ByteBuf byteBuf) throws Exception {
    byteBuf.writeShort(s.length());
    byteBuf.writeBytes(s.getBytes());
    channelHandlerContext.writeAndFlush(byteBuf);
}
Related