开发者

Handling received messages directly in the Client (using nio trough the netty-framework)

I have made an client - server example using netty. I have defined handlers for the server and the client. Basically I connect with the client to the server and send some messages. Every received message gets send back (with the content of the message being converted to upper case). All the work on the received messages, on server and client-side, is done by the defined handlers.

But I would like to use, or better receive/accept, some of the messages directly in the client not (just) in the handler. So my question is is it possible to have some listener to receive messages directly in the client-program and not in its handlers. The thin is I would like to access the received messages within the (executable) program (basically the class with a main method) that created a new client object, using something like a timer which (or a loop) which would periodically check for new messages.开发者_如何学C

I would appreciate if someone could help me with this issue. Or at least tell me if its even possible with netty .


You're looking to translate netty's event-based model into a polling model. A simple way to do that is to create a message queue:

//import java.util.concurrent.BlockingQueue;
//import java.util.concurrent.LinkedBlockingQueue;
BlockingQueue queue = new LinkedBlockingQueue();

You need to make the queue available to your handler as a constructor argument, and when a message arrives you put it into the queue:

// Your netty handler:
queue.put(message);

On the client end, you can poll the queue for messages:

// The polling loop in your program:
message = queue.poll(5, TimeUnit.SECONDS);

The BlockingQueue offers you the choice between waiting for a message to arrive (take()), waiting a certain amount of time for a message to arrive (poll(long, TimeUnit)), or merely checking whether any message is available right now (poll()).

From a design perspective, this approach kills the non-blocking IO advantage netty is supposed to give you. You could have used a normal Socket connection for the same net result.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜