Best way to send continuous data in Java using Netty
I'm planning to use Netty to design a TCP Server. When the client connects, I have to immediately start pumping XML dat开发者_如何学JAVAa 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.
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) {
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();
}
}
Doing a while/sleep would work, but would not be in the Netty super-scalable style. It would be thread-per-connection programming.
Instead, schedule a periodic job on an Executor that writes a message to the channel.
精彩评论