Best way to send continuous data in Java using Netty
Amit Phatarphekar
amitechforums at gmail.com
Thu Jul 21 19:32:01 EDT 2011
I'm planning to use Netty to design a TCP Server. When the client connects,
I have to immediately start pumping
XML data to the client continuously...for hours/days. Its that simple.
So, I override "channelConnected" method and send data from that method,
right?...thats great.
I will be using the following ChannelFactory
ChannelFactory factory =
new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(),
Executors.newCachedThreadPool());
NioServerSocketChannelFactory documentation says -> "A worker thread
performs non-blocking read and write for one or more Channels in a
non-blocking mode." Good.
According to effective Java "Item 51: Don't depend on the thread scheduler",
I want the worker thread to do a "unit of work" and then finish/return.
So in my case, though I have to send data continuously, I want to send some
chunk (lets say 1 MB ) and then be done (unit of work completed), so that
worker thread can return. Then I'll send another 1 MB.
Below example is from the official guide of Netty here ->
http://docs.jboss.org/netty/3.2/guide/html_single/index.html#d0e440
I guess the question is then, in this scenario, if i had to unconditionally
keep sending time to the client, how would I do it, considering
each send as a unit of work.
One way of doing it would be to just put a while loop and do a
Thread.Sleep. Any other way?
package org.jboss.netty.example.time;
public class TimeServerHandler extends SimpleChannelHandler {
@Override
public void channelConnected(ChannelHandlerContext ctx,
ChannelStateEvent e) {1
Channel ch = e.getChannel();
ChannelBuffer time = ChannelBuffers.buffer(4);
time.writeInt(System.currentTimeMillis() / 1000);
ChannelFuture f = ch.write(time);
f.addListener(new ChannelFutureListener() {
public void operationComplete(ChannelFuture future) {
Channel ch = future.getChannel();
ch.close();
}
});
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx,
ExceptionEvent e) {
e.getCause().printStackTrace();
e.getChannel().close();
}
}
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/netty-users/attachments/20110721/5faf047c/attachment.html
More information about the netty-users
mailing list