简体   繁体   English

如何从Netty向客户发送一个以上的回复

[英]How to send more then one response to client from Netty

I want to send more than one response to client based on back end process. 我想基于后端进程向client发送多个响应。 But in Netty examples I saw echo server is sending back the response at the same time. 但是在Netty示例中,我看到echo server正在同时发送回response

My requirement is, I need to validate the client and send him OK response, then send him the DB updates when available. 我的要求是,我需要验证客户端并向他发送OK响应,然后在可用时向他发送DB更新。

How can I send more responses to client ? 如何向client发送更多responses Pls direct me to an example or any guide? 请把我引到一个例子或任何指南?

at every point in your pipeline you can get the pipeline Channel object from the MessageEvent object (or ChannelEvent ) which is passed from handler to handler. 在管道中的每个点,您都可以从MessageEvent对象(或ChannelEvent )中获取管道Channel对象,该对象从处理程序传递到处理程序。 you can use this information to send multiple responses at different points in the pipeline. 您可以使用此信息在管道中的不同点发送多个响应。

if we take the echo server example as a base, we can add a handler which send the echo again (that can be done also in the same handler, but the example is to show that multiple handlers can respond). 如果以回显服务器示例为基础,则可以添加一个处理程序,该处理程序再次发送回显(也可以在同一处理程序中完成,但是该示例显示了多个处理程序可以响应)。

    public class EchoServerHandler extends ChannelHandlerAdapter {

        public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
           Channel ch = e.getChannel();
           // first message
           ch.write(e.getMessage());
        }
        // ...
    }

    public class EchoServerHandler2 extends ChannelHandlerAdapter {

           public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
           Channel ch = e.getChannel();
           // send second message     
           ch.write(e.getMessage());
        }
        // ...
    }

You can do that as long as you have the reference to the relevant Channel (or ChannelHandlerContext ). 只要您具有对相关Channel (或ChannelHandlerContext )的引用,就可以这样做。 For example, you can do this: 例如,您可以这样做:

public class MyHandler extends ChannelHandlerAdapter {
  ...
  public void channelRead(ctx, msg) {
    MyRequest req = (MyRequest) msg;
    ctx.write(new MyFirstResponse(..));
    executor.execute(new Runnable() {
      public void run() {
        // Perform database operation
        ..
        ctx.write(new MySecondResponse(...));
      }
    }
  }
  ...
}

You can do this as long as Netty doesn't close the Channel. 只要Netty不关闭渠道,您就可以这样做。 Its better you call close() yourself when you're done. 最好在完成后自己调用close()。

Here's a sample: https://stackoverflow.com/a/48128514/2557517 这是一个示例: https : //stackoverflow.com/a/48128514/2557517

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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