InBoundHandler向OutBoundHanlder傳資料

陈鸿圳發表於2024-05-27

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】的【】方法被呼叫,等下就是向【out bound handler】傳遞了資料了。

相關文章