从netty中的通道处理程序将值传递给主程序

Passing a value to the main program from a channel handler in netty

我正在使用 netty 编写一个客户端来处理自定义协议。我已经定义了一个扩展 SimpleChannelInboundHandler 的处理程序,它处理发送和接收消息。

public  class ClientHandler extends SimpleChannelInboundHandler {
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, Object o) throws Exception {
        log.info("Client received: " + ((ByteBuf)o).toString(CharsetUtil.UTF_8));
        System.out.println("Client received: " + ((ByteBuf)o).toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelActive(ChannelHandlerContext channelHandlerContext){
        log.info("Client sent: $"+ new MessageRequest().toString() +"$");
        channelHandlerContext.writeAndFlush(Unpooled.copiedBuffer((new MessageRequest().toString()), CharsetUtil.UTF_8));
    }


    @Override
    public void exceptionCaught(ChannelHandlerContext channelHandlerContext, Throwable cause){
        cause.printStackTrace();
        channelHandlerContext.close();
    }
}

此处理程序能够将响应打印到控制台。但是因为我正在编写一个将被另一个服务使用的客户端,所以我需要将响应发送到调用我的客户端的服务。

请帮助我将收到的响应发送给调用服务。

您可以将监听服务的引用存储在 ClientHandler class 中,然后调用该服务的 setMessage 方法 class 将来自channelRead0 处理程序的方法。

更好的方法是使用观察者模式