java - How to read Message in netty in other class -


i want read message @ specific position in class other inboundhandler. can't find way read expect in channelread0 method, called netty framework.

for example:

context.writemessage("message"); string msg = context.readmessage; 

if not possible, how can map result, in channelread0 method specific call made in class?

the netty framework designed asynchronously driven. using analogy, can handle large amount of connections minimal threading usage. creating api uses netty framework dispatch calls remote location, should use same analogy calls.

instead of making api return value direct, make return future<?> or promise<?>. there different ways of implementing system in application, simplest way creating custom handler maps incoming requests promises in fifo queue.

an example of following:

this heavily based on this answer submitted in past.

we start out handler maps requests requests in our pipeline:

public class mylasthandler extends simpleinboundhandler<string> {     private final synchronousqueue<promise<string>> queue;      public mylasthandler (synchronousqueue<promise<string>> queue) {         super();         this.queue = queue;     }      // following called messagereceived(channelhandlercontext, string) in 5.0.     @override     public void channelread0(channelhandlercontext ctx, string msg) {         this.queue.remove().setsuccss(msg);          // or setfailure(throwable)     } } 

we need have method of sending commands remote server:

channel channel = ....; synchronousqueue<promise<string>> queue = ....;  public future<string> sendcommandasync(string command) {     return sendcommandasync(command, new defaultpromise<>()); }  public future<string> sendcommandasync(string command, promise<string> promise) {     synchronized(channel) {         queue.offer(promise);         channel.write(command);     }     channel.flush(); } 

after have done our methods, need way call it:

sendcommandasync("user anonymous",      new defaultpromise<>().addlistener(         (future<string> f) -> {             string response = f.get();             if (response.startwidth("331")) {                 //             }             // etc         }     ) ); 

if called use our api blocking call, can that:

string response = sendcommandasync("user anonymous").get(); if (response.startwidth("331")) {     // } // etc 

notice future.get() can throw interruptedexception if thread state interrupted, unlike socket read operation, can cancelled interaction on socket. exception should not problem in futurelistener.


Comments