【发布时间】: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();
}
}
此处理程序能够将响应打印到控制台。但是由于我正在编写一个将由另一个服务使用的客户端,所以我需要将响应发送到调用我的客户端的服务。
请帮助我将收到的响应发送给呼叫服务。
【问题讨论】:
-
它是异步的,因此您需要使用某种形式的回调机制来向服务“返回”一个值。但是您需要选择它的工作方式,例如简单的callback interface、elaborate event system、EventBus 甚至类似RxJava。
标签: java asynchronous netty