New to netty

Frederic Bregier fredbregier at free.fr
Fri Dec 12 11:14:58 EST 2008


Hi,

I was probably not enough clear. So let me show a very small example:

Main.class

void mymethod() {
   ClientBootStrap bootstrap = new ClientBootStrap();
   LinkedBlockingQueue<MyMsg> queue = new LinkedBlockingQueue<MyMsg>()
   ChannelPipeline p = b.getPipeline();
   // Add handlers to the pipeline.
   p.addLast("encoder", new ObjectEncodingHandler());
   p.addLast("decoder", new ObjectDecodingHandler());
   MyMsg tosend = new MyMsg(...);
   p.addLast("logic",   new MyChannelHandler(queue, tosend));
   bootstrap.connect(...);
   MyMsg msg = queue.take();
   // do something now with msg
   businessDo(msg);
}

Then
MyChannelHandler.class

MyChannelHandler(LinkedBlockingQueue<MyMsg> queue, MyMsg msg) {
  this.queue = queue;
  this.msg = msg;
}
void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
   ctx.getChannel().write(this.msg); 
}

void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   // get the message
   MyMsg msg = (MyMsg) e.getMessage()
   queue.put(msg);
   // now I close the connection since it is no more useful
   ctx.getChannel().close()
}


If you want to keep the connection, then simply have the following.

Main.class

void mymethod() {
   ClientBootStrap bootstrap = new ClientBootStrap();
   ChannelPipeline p = b.getPipeline();
   // Add handlers to the pipeline.
   p.addLast("encoder", new ObjectEncodingHandler());
   p.addLast("decoder", new ObjectDecodingHandler());
   MyMsg tosend = new MyMsg(...);
   p.addLast("logic",   new MyChannelHandler(queue, tosend));
   bootstrap.connect(...);
   // wait on close of the connection (see the API)
}

Then
MyChannelHandler.class

MyChannelHandler(MyMsg msg) {
  this.msg = msg;
}
void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) {
   ctx.getChannel().write(this.msg); 
}

void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
   // get the message
   MyMsg msg = (MyMsg) e.getMessage()
   // do something now with msg
   businessDo(msg);
}

In this last version, you will have to deal when you want to close the
connection
according to your business and when you want to send a new message to the
server and what kind of message...

HTH,
Frederic

-----
Hardware/Software Architect
-- 
View this message in context: http://n2.nabble.com/New-to-netty-tp1625621p1648419.html
Sent from the Netty User Group mailing list archive at Nabble.com.




More information about the netty-users mailing list