mina-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From "Brigham Stevens" <...@vikingmind.com>
Subject RE: Simple UDP example?
Date Wed, 23 May 2007 01:46:42 GMT
One thing that I learned from implementing a UDP client and server with
Mina, and from the tips on this list, it is really just the same as a TCP
server.

The key differences are in setup. The other thing I found out is you have to
implement your own SessionRecycler which is really easy. You need to do this
because the default one times out your sessions. I am not sure if my session
recycler is 100%, and I have been meaning to ask some questions about that
on the list, but I can send it to you if you want. It seems to work 100% for
my testing.

Here is some working code that sets up the server, the client is very
similar except instead of a UDPAcceptor you use a UDPConnector, but I pasted
my client setup code too... Then just look at the TCP examples for
implementing a IoHandler adapter and your Codecs + Factory and you should be
all set.

//
//  UDPContext extends a mina IoHandlerAdapter, just like for TCP
//
static void startUDPServer(Args args, UDPContext context) throws Throwable {
        // load the global arguments

        // create an acceptor with 3 IO processor threads (on a dual core)
        IoAcceptor acceptor = new
DatagramAcceptor(Executors.newCachedThreadPool());

        // configure the thread models
        IoServiceConfig acceptorConfig = acceptor.getDefaultConfig();

        acceptorConfig.setThreadModel(ThreadModel.MANUAL);

        // Prepare the service configuration.
        DatagramAcceptorConfig cfg  = new DatagramAcceptorConfig();
        DatagramSessionConfig  dcfg = cfg.getSessionConfig();

        dcfg.setTrafficClass(0x10);     /** IPTOS_LOWDELAY */
        dcfg.setReuseAddress(true);
        cfg.setSessionRecycler(new SimpleRecycler());

        // turn on MBean Support
//      IoServiceManager serviceManager = new IoServiceManager( acceptor );
//      serviceManager.startCollectingStats(5000);
//      MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
//      ObjectName name = new
ObjectName("mina.core.server:type=IoServiceManager");
//      mbs.registerMBean(serviceManager, name);
//      
        // turn on app remote monitoring and control
//      ServerManager mgr = new ServerManager(context);
//      ObjectName name2 = new ObjectName("MyServer
Server:type=ServerManager");
//      mbs.registerMBean(mgr, name2);

        // add filters
        DefaultIoFilterChainBuilder filterChainBuilder =
cfg.getFilterChain();

// Change this next line to point to your own CodecFactory

        filterChainBuilder.addLast("codec", new ProtocolCodecFilter(new
MsgProtocolCodecFactory()));
        LoggingFilter lf = new LoggingFilter();

        filterChainBuilder.addLast("logger", lf);

        //
        // Create our IO Handler thread pool
        //
        int                maxThreads      =
args.getInt("server.max.threads", 10);
        int                coreThreads     =
args.getInt("server.core.threads", 5);
        int                threadKeepAlive =
args.getInt("server.thread.keepalive.seconds", 60);
        ThreadPoolExecutor threadPool      = new
ThreadPoolExecutor(coreThreads, maxThreads, threadKeepAlive,
TimeUnit.SECONDS, new SynchronousQueue<Runnable>(true), new
MyThreadFactory());

        if (args.getBool("server.core.thread.prestart", true)) {
            context.logger.info("Prestarting Core Threads:" + coreThreads);
            threadPool.prestartAllCoreThreads();
        }

        filterChainBuilder.addLast("threadPool", new
ExecutorFilter(threadPool));

        // Start the listener
        InetSocketAddress address = new
InetSocketAddress(InetAddress.getByName(bindAddress), port);

        acceptor.bind(address, context, cfg);
        context.logger.info("Server Listening on: UDP " +
address.toString());
    }
 

Here is how to setup the client:

        UPDConnector = new
DatagramConnector(Executors.newCachedThreadPool(new
MyThreadFactory("BelterCOnnector")));

        // Set buffering to and non-pooled buffers
        // non pooled buffers perform way faster
        ByteBuffer.setAllocator(new SimpleByteBufferAllocator());
        ByteBuffer.setUseDirectBuffers(false);


        PropertyConfigurator.configureAndWatch("conf/log4j.cfg");
        logger = LoggerFactory.getLogger(YourClass.class);

        // Prepare the service configuration.
        dcfg = UPDConnector.getDefaultConfig();
        dcfg.setSessionRecycler(new SimpleRecycler());

        dscfg = (DatagramSessionConfig) dcfg.getSessionConfig();

        dscfg.setTrafficClass(0x10);   /** IPTOS_LOWDELAY */
        dscfg.setReuseAddress(true);

        // Configure the service.
        DefaultIoFilterChainBuilder f1 = (DefaultIoFilterChainBuilder)
dcfg.getFilterChain();

        f1.addLast("codec", new ProtocolCodecFilter(new
MsgProtocolCodecFactory()));
        f1.addLast("logger", new LoggingFilter());


And here is how you connect the client:


            InetSocketAddress addr   = new InetSocketAddress(hostName,
port);

            // TODO: do we need to specify the local address here to ensure
the SimpleSession thing works?
            ConnectFuture     future = UPDConnector.connect(addr,
YourIOHandlerAdapterHere, dcfg);



# -----Original Message-----
# From: Mark Webb [mailto:elihusmails@gmail.com] 
# Sent: Tuesday, May 22, 2007 6:21 PM
# To: dev@mina.apache.org
# Subject: Re: Simple UDP example?
# 
# I have been working on a tutorial.  Unfortunately my job 
# keeps getting in the way :).  If you need any help, contact 
# me offline as I have some working code laying around...
# 
# 
# On 5/22/07, James Apfel <james.apfel@gmail.com> wrote:
# >
# > Hi,
# >
# > I have an existing NIO/UDP based application which I would like to 
# > switch to MINA and I'm looking for a good example that demonstrates 
# > how somebody would do it in MINA.
# >
# > Thanks
# > J.A.
# >
# 
# 
# 
# --
# ..Cheers
# Mark
# 


Mime
View raw message