【问题标题】:Passing a value to the main program from a channel handler in netty从 netty 中的通道处理程序将值传递给主程序
【发布时间】:2019-03-22 07:37:24
【问题描述】:

我正在编写一个使用 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();
    }
}

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

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

【问题讨论】:

标签: java asynchronous netty


【解决方案1】:

您可以将侦听服务的引用存储在您的ClientHandler 类中,并调用服务类的setMessage 方法以将来自处理程序的channelRead0 方法的消息提供给它。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 2017-12-30
    • 1970-01-01
    • 2010-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多