netty:InBoundHandler向OutBoundHanlder传数据

pipeline,注意out handler要在in handler之前

// out handler
socketChannel.pipeline().addLast(new StringEncoder());
socketChannel.pipeline().addLast(new MyServerChannelOutBoundHandler());
// in handler
socketChannel.pipeline().addLast(new StringDecoder());
socketChannel.pipeline().addLast(new MyServerChannelInBoundHandler());

【MyServerChannelInBoundHandler.java】

@Slf4j
public class MyServerChannelInBoundHandler extends SimpleChannelInboundHandler<String>
{
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        log.info("MyChannelInBoundHandler.channelActive[" + ctx.channel().remoteAddress() + "]: ");
        ctx.write("I'm server, thanks for connected!\r\n");    // 这一句会触发out handler的write方法
        ctx.flush();                                           // 这一句会触发out handler的flush方法
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        log.info("MyChannelInBoundHandler.channelReadComplete[" + ctx.channel().remoteAddress() + "]");
        super.channelReadComplete(ctx);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) {
        log.info("MyChannelInBoundHandler.channelRead0[" + ctx.channel().remoteAddress() + "]:" + msg);
        ctx.writeAndFlush(String.format("server have received data from you:[%s]", msg.trim()));
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) {
        log.info("MyChannelInBoundHandler.channelInactive[" + ctx.channel().remoteAddress() + "]: ");
    }
}

【MyServerChannelOutBoundHandler.java】

@Slf4j
public class MyServerChannelOutBoundHandler extends ChannelOutboundHandlerAdapter
{
    @Override
    public void read(ChannelHandlerContext ctx) throws Exception {
        log.info("MyChannelOutBoundHandler.read[" + ctx.channel().remoteAddress() + "]: ");
        super.read(ctx);
    }

    @Override
    public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
        log.info("MyChannelOutBoundHandler.write[{}]: {}", ctx.channel().remoteAddress(), msg);
        super.write(ctx, msg, promise);
    }

    @Override
    public void flush(ChannelHandlerContext ctx) throws Exception {
        log.info("MyChannelOutBoundHandler.flush[" + ctx.channel().remoteAddress() + "]: ");
        super.flush(ctx);
    }
}

当【in bound handler】里面的【write、writeAndFlush】方法被调用时,会触发【out bound handler】的【write、flush】方法被调用,等于就是向【out bound handler】传递了数据了。

posted @ 2024-05-27 22:15  陈鸿圳  阅读(57)  评论(0)    收藏  举报