开发者

DelimiterBasedFrameDecoder, how does it works?

开发者 https://www.devze.com 2023-03-17 14:51 出处:网络
i premiss that i am a newbie of netty; i am trying to create a client to an external server, this server outputs messages that terminates with 0x0d so i decide to use the DelimiterBasedFrameDecoder to

i premiss that i am a newbie of netty; i am trying to create a client to an external server, this server outputs messages that terminates with 0x0d so i decide to use the DelimiterBasedFrameDecoder to handle these messages.

This is just a test of the handler:

public class TestHandler extends DelimiterBasedFrameDecoder {

    public TestHandler(){

        super(200, true, ChannelBuffers.wrappedBuffer(new byte[] { 开发者_如何学Go0x0d }));

    }

    @Override
    protected Object decode(ChannelHandlerContext ctx, Channel ch,
            ChannelBuffer cbuf) throws Exception {


        ByteBuffer buf = ByteBuffer.allocate(cbuf.readableBytes());

        cbuf.readBytes(buf);

        byte[] data = buf.array();

        for(byte b : data){

            System.out.print(b + " ");

        }

        System.out.println();

            ...... (some other code)

     }

what i see wrong from this is that it doesn't strip the delimiter as i specified in the constructor; at the end of the byte[] data i always have the 0x0d; So, just as test, i changed the delimiter in the constructor putting on it a test value like 0x55

super(200, true, ChannelBuffers.wrappedBuffer(new byte[] { 0x55 }));

and it works in the same way, there is not difference from before. I think i am using it in the wrong way, or i am reading the data in the wrong way. What is the right way to use this class?

To be clear, in the real code from this handler i create an object from the read data and i return this object from the decode() method, then i have another handler that extends SimpleChannelHandler that get this object ( it is similar to the example in the user guide ).

Thanks for the help Bye


I think your decode method is not using the "stripBytes" part of the constructor properly.

If you check out the code in DelimiterBasedFrameDecoder of Netty, you will see the following if condition in code, which is missing in your overriden decode method. This is causing the bytes not to be stripped.

 if (stripDelimiter) {
            frame = buffer.readBytes(minFrameLength);
            buffer.skipBytes(minDelimLength);
        } else {
            frame = buffer.readBytes(minFrameLength + minDelimLength);
        }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号