MINA Quick Start

Source: Internet
Author: User
Tags stack trace time in milliseconds

Original sync to: http://www.waylau.com/mina-quick-start/

Apache MINA is a network application framework that can help users develop high-performance, highly scalable Web applications. It provides an abstract event-driven asynchronous API for use on different transport protocols, such as TCP/IP and UDP/IP, via Java NIO.

This tutorial shows you how to build a process for MINA-based apps. This tutorial is about building a time server.

This tutorial requires the following prerequisites:

    • MINA 2.0 +
    • JDK 1.5 +
    • SLF4J 1.3.0 +
      • LOG4J 1.2 Users: Slf4j-api.jar, Slf4j-log4j12.jar and log4j 1.2.x
      • LOG4J 1.3 Users: Slf4j-api.jar, Slf4j-log4j13.jar and log4j 1.3.x
      • Java.util.logging users: Slf4j-api.jar and Slf4j-jdk14.jar
      • Important: Make sure you're using a slf4j-*.jar that matches your log frame.

For example, if Slf4j-log4j12.jar and Log4j-1.3.x.jar are used together, a failure will occur

Environment

This sample development environment is:

    • Maven 3.2.x
    • Eclipse 4.x

You can choose any IDE you like.

Writing MINA time servers

Let's start by creating a file called Minatimeserver.java. The initialization code is as follows:

public class MinaTimeServer {    public static void main(String[] args) {        // code will go here next    }}

This procedure is simple and straightforward for everyone. We have simply defined a main method for starting the program. Now, let's start adding the code that makes up our server. First, we need an object to listen for incoming connections. Because this program is based on TCP/IP, we have added Socketacceptor to the program.

Import Org.apache.mina.transport.socket.nio.NioSocketAcceptor;

public class MinaTimeServer{    public static void main( String[] args )    {        IoAcceptor acceptor = new NioSocketAcceptor();    }}

Niosocketacceptor class is ready, we continue to define the processing class and bind Niosocketacceptor to a port:

import java.net.InetSocketAddress;import org.apache.mina.core.service.IoAcceptor;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;public class MinaTimeServer{    private static final int PORT = 9123;    public static void main( String[] args ) throws IOException    {        IoAcceptor acceptor = new NioSocketAcceptor();        acceptor.bind( new InetSocketAddress(PORT) );    }}

As you can see, there is a about acceptor.setlocaladdress (new inetsocketaddress (PORT)); of the call. This method defines the host and port to be heard by this server. The last method is a ioacceptor.bind () call. This method binds to the specified port and begins processing the remote client request.

Next we add a filter to the configuration. This filter will log all information, such as the new session, the received message, the message sent, the session closed. The next filter is a protocolcodecfilter. This filter translates binary or protocol-specific data into a message object and vice versa. We use an existing TextLine factory because it will handle text-based messages for you (you do not have to write the codec section).

  Import Java.io.ioexception;import java.net.inetsocketaddress;import java.nio.charset.charset;import Org.apache.mina.core.service.ioacceptor;import Org.apache.mina.filter.codec.protocolcodecfilter;import Org.apache.mina.filter.codec.textline.textlinecodecfactory;import Org.apache.mina.filter.logging.LoggingFilter; Import Org.apache.mina.transport.socket.nio.niosocketacceptor;public class minatimeserver{public static void main (St        Ring[] args) {Ioacceptor acceptor = new Niosocketacceptor ();        Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ()); Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory (Charset.forname ("        UTF-8 ")));    Acceptor.bind (New Inetsocketaddress (PORT)); }}

Next, we will define the processor to use for the service client connection and the current time of the request. The processor class is a class that must implement the Iohandler interface. For almost all programs that use MINA, this will become the main work of the program, as it will serve all requests from the client. In this article we will extend the Iohandleradapter class. This class follows the adapter design pattern, simplifying the amount of code that needs to be written to satisfy the need to pass the Iohandler interface in a class.

import java.net.InetSocketAddress;import java.nio.charset.Charset;import org.apache.mina.core.service.IoAcceptor;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;public class MinaTimeServer{    public static void main( String[] args ) throws IOException    {        IoAcceptor acceptor = new NioSocketAcceptor();        acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );        acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));        acceptor.setHandler(  new TimeServerHandler() );        acceptor.bind( new InetSocketAddress(PORT) );    }}

Now we add the configuration in the Niosocketacceptor. This will allow us to make socket-specific settings for the socket used to receive client connections.

Import Java.net.inetsocketaddress;import Java.nio.charset.charset;import org.apache.mina.core.session.IdleStatus; Import Org.apache.mina.core.service.ioacceptor;import Org.apache.mina.filter.codec.protocolcodecfilter;import Org.apache.mina.filter.codec.textline.textlinecodecfactory;import Org.apache.mina.filter.logging.LoggingFilter; Import Org.apache.mina.transport.socket.nio.niosocketacceptor;public class minatimeserver{public static void main (St        Ring[] args) throws IOException {Ioacceptor acceptor = new Niosocketacceptor ();        Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ()); Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory (Charset.forname ("        UTF-8 ")));        Acceptor.sethandler (New Timeserverhandler ());        Acceptor.getsessionconfig (). Setreadbuffersize (2048);        Acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 10); Acceptor.bind (New Inetsocketaddress (PORT)); }}

Two new lines are added to the Minatimeserver class. These methods set the Iohandler, set the input buffer size for the session, and the Idle property. Specifies the buffer size to inform the underlying operating system how much space is allocated for incoming data. The second line specifies when to check the idle session. In the call to Setidletime, the first parameter defines the behavior to check if the session is idle, and the second parameter defines the length of time in milliseconds that must occur before the session is considered idle.

The processor code is as follows:

  Import Java.util.date;import org.apache.mina.core.session.idlestatus;import Org.apache.mina.core.service.iohandleradapter;import Org.apache.mina.core.session.iosession;public Class Timeserverhandler extends iohandleradapter{@Override public void Exceptioncaught (iosession session, Throwable Caus    E) throws Exception {cause.printstacktrace ();  } @Override public void messagereceived (iosession session, Object message) throws Exception {String str        = Message.tostring ();            if (Str.trim (). Equalsignorecase ("quit")) {session.close ();        Return        } Date Date = new Date ();        Session.write (Date.tostring ());    System.out.println ("Message written ..."); } @Override public void Sessionidle (iosession session, Idlestatus status) throws Exception {System.out.    println ("IDLE" + session.getidlecount (status)); }}

The methods used in this class are Exceptioncaught, messagereceived, and Sessionidle. Exceptioncaught should always be defined in the processor to handle exceptions thrown when the normal remote connection process occurs. If this method is not defined, the exception may not be reported correctly.

The Exceptioncaught method will print a simple stack trace for errors and session closures. For more programs, this will be normal unless the processor is able to recover from an exceptional situation.

The Messagereceived method receives data from the client and writes the current time back to the client. If the message received from the client is the word "quit", the current session will be closed. This method also prints out the current time to the client. Depending on the protocol codec you are using, the object passed to this method (the second parameter) will be different, just like the object you passed to the Session.write (object) method. If you do not define a protocol encoder, you will likely receive a Iobuffer object and be asked to write a Iobuffer object.

Once the session remains idle, it reaches Acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 10); The Sessionidle method is called for the defined length of time.

The rest of the work is to define the socket address that the server will listen to and make a call to start the service. The code looks like this:

Import Java.io.ioexception;import Java.net.inetsocketaddress;import Java.nio.charset.charset;import Org.apache.mina.core.service.ioacceptor;import Org.apache.mina.core.session.idlestatus;import Org.apache.mina.filter.codec.protocolcodecfilter;import Org.apache.mina.filter.codec.textline.textlinecodecfactory;import Org.apache.mina.filter.logging.LoggingFilter; Import Org.apache.mina.transport.socket.nio.niosocketacceptor;public class minatimeserver{private static final int PO    RT = 9123;        public static void Main (string[] args) throws IOException {Ioacceptor acceptor = new Niosocketacceptor ();        Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ()); Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory (Charset.forname ("        UTF-8 ")));        Acceptor.sethandler (New Timeserverhandler ());        Acceptor.getsessionconfig (). Setreadbuffersize (2048); Acceptor.getsessionconfig (). Setidletime (idlestatus.bOth_idle, 10);    Acceptor.bind (New Inetsocketaddress (PORT)); }}
Test time Server

Now let's start compiling the program. Once you have compiled the program you can run it and you can test what will happen. The simplest way to test a program is to start the program and then telnet to the program:

Client Output service-Side output
[Email protected]:~> telnet 127.0.0.1 9123
Trying 127.0.0.1 ...
Connected to 127.0.0.1.
Escape character is ' ^] '.
Hello
Wed Oct 23:23:36 EDT 2007
Quit
Connection closed by foreign host.
[Email protected]:~>
MINA time server started.
Message written ...

Source

Translator Note: Translated version of the project source see Https://github.com/waylau/apache-mina-2-user-guide-demos in the com.waylau.mina.demo.time package

What's next?

From the example above, you can write a NIO server based on MINA very simply. If you already have an interest in MINA, you can continue to read other tutorials, such as the Apache MINA 2 User Guide. In the JAVA world, similar NIO frameworks also have Netty, which can be consulted in the Netty 4.x user Guide. Interestingly, the two frameworks are the same author.

MINA Quick Start

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.