简体   繁体   中英

Netty Asynchronous Responses by Server Handler

A server handler. For each received message, there will be multiple responses. Business Logic involves putting the requests in a queue, removing from the queue, processing the requests and responding.

How do i process requests asynchronously, respond asynchronously while maintaining the integrity of the queue?

The code below is behaves synchronously.

public class TestHandler extends SimpleChannelHandler {

    @Override
    public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception {
        // Send greeting for a new connection.
        e.getChannel().write(
                "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n");
        e.getChannel().write("It is " + new Date() + " now.\r\n");

    }

    @Override
    public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {      
        String XMLFromClient = (String) e.getMessage() ;

        ReadXML2 rx = new ReadXML2();
        String response = null;
        response = rx.processInput(XMLFromClient);
        ChannelFuture future = e.getChannel().write(response);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) {
        e.getCause().printStackTrace();
        Channel ch = e.getChannel();
        ch.close();
    } 
}

In netty writes are always asynchronous, but messages written to the same channel will be queued up in sequence. While reading, if you want asynchronous operation then you need to add an ExecutionHandler to the ChannelPipeline . If ordering is important then use the the OrderedMemoryAwareThreadPoolExecutor implementation. You need to add it to the ChannelPipeline ahead of your own TestHandler . The new Netty 4 API provides better control over async pipeline handlers, but it is still under development.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM