10 - EmbeddedChannel-测试ChannelHandler链

方法职责
writeInbound(Object... msgs)将入站消息写入到EmbeddedChannel中
readInbound()从EmbeddedChannel中读取一个入站消息,任何返回的消息都穿过了整个ChannelPipeLine
writeOutbound(Object... msgs)将出站消息写入到EmbeddedChannel中
readOutbound()从EmbeddedChannel中读取一个出站消息,任何返回的消息都穿过了整个ChannelPipeLine

10.1 示例

//测试结果
Received message:0
Received Finished!
Received message:1
Received Finished!
Received message:2
Received Finished!
embeddedChannel readInbound:0
embeddedChannel readInbound:1
embeddedChannel readInbound:2
public class EmBeddedChannelTest {
    public static void main(String[] args) {
        ByteBuf byteBuf = Unpooled.buffer();
        for (int i = 0; i < 3; i++) {
            byteBuf.writeInt(i);
        }

        EmbeddedChannel embeddedChannel = new EmbeddedChannel();
        
        //获取channelPipeLine
        ChannelPipeline channelPipeline = embeddedChannel.pipeline();
        channelPipeline.addLast(new SimpleChannelInBoundHandlerTest());
        channelPipeline.addFirst(new DecodeTest());

        //写入测试数据
        embeddedChannel.writeInbound(byteBuf);
        
        System.out.println("embeddedChannel readInbound:"+embeddedChannel.readInbound());
        System.out.println("embeddedChannel readInbound:"+embeddedChannel.readInbound());
        System.out.println("embeddedChannel readInbound:"+embeddedChannel.readInbound());

    }

}

//解码器
class DecodeTest extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> out) throws Exception {
        if( in.readableBytes()>=4 ){
            out.add(in.readInt());
        }
    }
}

//channelHandler
class  SimpleChannelInBoundHandlerTest extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, Object msg) throws Exception {
        System.out.println("Received message:"+msg);
        System.out.println("Received Finished!");
        ctx.fireChannelRead(msg);
    }
}

转载于:https://www.cnblogs.com/Desneo/p/7326393.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值