Best way to send continuous data in Java using Netty

Amit Phatarphekar amitechforums at gmail.com
Fri Jul 22 13:04:11 EDT 2011


Ok.  I'll let me ask the question a little differently - "How do I send data
to the client continuously?".


In the code below I'm trying to send localtime every 5 secs to the client
from within channelConnected method.
But it doesn't work for me.  It works only if I comment the while loop.
So if I want to send client time every 5 secs how do i do it?

        public class SRNGServer {

            public static void main(String[] args) throws Exception {
                // Configure the server.
                ServerBootstrap bootstrap = new ServerBootstrap(
                        new NioServerSocketChannelFactory(
                                Executors.newCachedThreadPool(),
                                Executors.newCachedThreadPool()));

                // Configure the pipeline factory.
                bootstrap.setPipelineFactory(new
SRNGServerPipelineFactory());

                // Bind and start to accept incoming connections.
                bootstrap.bind(new InetSocketAddress(8080));
            }
        }



        public class SRNGServerHandler extends SimpleChannelUpstreamHandler
{

            private static final Logger logger = Logger.getLogger(
                    SRNGServerHandler.class.getName());


            @Override
            public void channelConnected(
                    ChannelHandlerContext ctx, ChannelStateEvent e) throws
Exception {
                // Send greeting for a new connection.
              ChannelFuture writeFuture=e.getChannel().write("Welcome to " +
InetAddress.getLocalHost().getHostName() + "!\r\n");


              while(true){
                e.getChannel().write("It is " + new Date() + " now.\r\n");

                Thread.sleep(1000*5);
              }
            }

            @Override
            public void exceptionCaught(
                    ChannelHandlerContext ctx, ExceptionEvent e) {
                logger.log(
                        Level.WARNING,
                        "Unexpected exception from downstream.",
                        e.getCause());
                e.getChannel().close();
            }
        }



        public class SRNGServerPipelineFactory implements
                ChannelPipelineFactory {

            public ChannelPipeline getPipeline() throws Exception {
                // Create a default pipeline implementation.
                ChannelPipeline pipeline = pipeline();

                pipeline.addLast("encoder", new StringEncoder());
                pipeline.addLast("handler", new SRNGServerHandler());

                return pipeline;
            }
        }


On Fri, Jul 22, 2011 at 2:07 AM, Ioan Eugen Stan <stan.ieugen at gmail.com>wrote:

> 2011/7/22 Amit Phatarphekar <amitechforums at gmail.com>:
> > 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();
> >             }
> >         }
> >
> >
> > _______________________________________________
> > netty-users mailing list
> > netty-users at lists.jboss.org
> > https://lists.jboss.org/mailman/listinfo/netty-users
> >
>
> I didn't understand what exactly is the question, but from what I know
> you should have no problems sending data continuously for long periods
> of time. And the amount you mentioned is not that large if we are
> talking about Ethernet speeds. You should give it a try and see what
> happens. If you run into trouble, seek help.
>
> I don't think the sleep is necessary. Reading and writing in Netty is
> done when there is data available and when it's room in the buffer.
>
> Hope that helps,
> --
> Ioan Eugen Stan
> http://ieugen.blogspot.com/
>
> _______________________________________________
> netty-users mailing list
> netty-users at lists.jboss.org
> https://lists.jboss.org/mailman/listinfo/netty-users
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://lists.jboss.org/pipermail/netty-users/attachments/20110722/38d72936/attachment.html 


More information about the netty-users mailing list