0

I am writing a client using netty for handling custom protocol. I have defined a handler which extends SimpleChannelInboundHandler which handles both sending and receiving message.

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();
    }
}

This handler is able to print the response to the console. But since I am writing an client which will be used by another service, I need to send the response to the service which is calling my client.

Kindly help me in sending the response received to the calling service.

Sarath Subu
  • 113
  • 9
  • 1
    It's asynchronous, so you'll need to use some form of callback mechanism to "return" a value to the service. But you'll need to chose how it should work, could be for example a simple [callback interface](https://stackoverflow.com/questions/18279302/how-do-i-perform-a-java-callback-between-classes), an [elaborate event system](https://github.com/iluwatar/java-design-patterns/tree/master/event-driven-architecture), [EventBus](https://github.com/google/guava/wiki/EventBusExplained) or even something like [RxJava](https://stackoverflow.com/q/42118782/995891). – zapl Oct 17 '18 at 16:06

1 Answers1

0

You can store the reference of your listening service in your ClientHandler class and call a setMessage method of the service class to give it the message from the channelRead0 method of your handler.

A better approach would be to use the Observer pattern

Riyafa Abdul Hameed
  • 7,417
  • 6
  • 40
  • 55