Apache Mina Study Notes (2)-Basics

Source: Internet
Author: User
Tags object serialization log4j
In the first chapter, we have a general understanding of Mina, and in this chapter we will make a detailed analysis of the client/server model in Mina. Some examples based on TCP,UDP are also provided.

Application structure

Service-side structure
Client structure

A Simple TCP server
A Simple TCP client
A simple UDP server
A simple UDP client

Summarize application Structure

An application structure that uses the Mina framework is as follows:

As you can see, Mina, as a middle tier, connects to your application and to the bottom of the network, it can handle tcp,udp even a serial communication protocol (RS-232C), so you can focus more on designing your application on Mina without needing to understand the complexity of the underlying network traffic.

Here's a look at the inside of Mina:

Generally speaking, Mina applications are divided into three tiers.

I/O Services-true I/O operations
I/O filter chain-Filter/Transfer data
I/O Handler-the logic of completing the program here

So, to create a Mina application, you just need to do:

Create I/O service-Select the service you have provided (acceptor) or the service you created yourself
Create a filter chain-select the filter chain already provided or create your own custom filter chain
Create I/ohandler-write business logic, handle a variety of different messages above is the overall structure of Mina,

Here's a look at the service-side structure:

In a nutshell, there is an I/O acceptor that listens for incoming connections or packets on the server, a new session is created for a new connection, and a subsequent request from that connection is processed in the session. All packages are accepted by the session and are indicated by the filter chain. The filter chain is used to modify the contents of the package (such as converting to objects, adding or rejecting some information). Finally these pack friends Iohandler deal with. It is also important to note that when a connection arrives, a session is created, regardless of whether or not the connection is successful at the end of the session.

Here is the client model:



The

client and the server are exactly the opposite state.

where clients will have a ioconnector to connect to the server. And all the processing still has iohandler done.

Simple TCP server

, create a simple TCP server as a demonstration: first you need to import some of the required packages into the IDE or configure your classpath, the specific method is not detailed, the required packages are:

MINA 2. X Core
JDK 1.5 or greater
slf4j 1.3.0 or greater

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 an D Slf4j-jdk14.jar
Important:please Make sure is using the right Slf4j-*.jar that matches to your logging Framewor K.

After the preparation is done, we begin to write the code

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));      }  }

Next, we add the configuration of the filter chain in the above code.

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 (string[] args) {Ioacceptor acceptor = new Nio          Socketacceptor ();  Acceptor.getfilterchain (). AddLast ("Logger", New Loggingfilter ()); This will create all the log information Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Textlinecodecfactory (Cha Rset.forname ("UTF-8")));      The second filter is used to pass the data acceptor.bind (new Inetsocketaddress (PORT)); }  }

Next, we need to define the handler used to process the message, and the handler class must implement the Iohandler interface. In Mina, this handler is the key to program development, in this teaching, we will inherit from Iohandleradapter.

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 sess      Ion, Throwable cause) throws Exception {cause.printstacktrace (); } @Override public void messagereceived (iosession session, Object message) throws Exception {St          Ring 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 {Sys      Tem.out.println ("IDLE" + session.getidlecount (status)); }  }

Finally, the complete server code is as follows:

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 PORT = 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 ());      Here set Handler Acceptor.getsessionconfig (). Setreadbuffersize (2048); This is the set ssesion buffer Acceptor.getsessionconfig (). Setidletime (Idlestatus.both_idle, 10);      Acceptor.bind (New Inetsocketaddress (PORT)); }  }

Run the server and open the Terminal Input command: Telnet 127.0.0.1 9123 will see that when you enter any character other than "quit", the server returns the current time to the terminal.

Simple TCP client

Import java.net.InetSocketAddress;  Import org.apache.mina.core.RuntimeIoException;  Import Org.apache.mina.core.future.ConnectFuture;  Import org.apache.mina.core.session.IoSession;  Import Org.apache.mina.example.sumup.codec.SumUpProtocolCodecFactory;  Import Org.apache.mina.filter.codec.ProtocolCodecFilter;  Import Org.apache.mina.filter.codec.serialization.ObjectSerializationCodecFactory;  Import Org.apache.mina.filter.logging.LoggingFilter;       Import Org.apache.mina.transport.socket.nio.NioSocketConnector;    /** * (<strong>entry point</strong>) starts SumUp client. * * @author <a href= "http://mina.apache.org" >apache Mina project</a> * * public class Client {p            Rivate static final String HOSTNAME = "localhost";           private static final int PORT = 8080; Private static final long connect_timeout = 30*1000l;        Seconds//Set this to False to use object serialization instead of custom codec. Private STATic Final Boolean use_custom_codec = true; public static void Main (string[] args) throws Throwable {if (args.length = = 0) {System.out.pri                Ntln ("Specify the list of any integers");            Return            }//Prepare values to sum up int[] values = new Int[args.length];            for (int i = 0; i < args.length; i++) {Values[i] = Integer.parseint (Args[i]);                } niosocketconnector connector = new Niosocketconnector ();            Configure the service.            Connector.setconnecttimeoutmillis (connect_timeout); if (USE_CUSTOM_CODEC) {
Connector.getfilterchain (). AddLast ("Codec", New Protocolcodecfilter (            New Sumupprotocolcodecfactory (false))); } else {Connector.getfilterchain (). AddLast ("Codec", new Pro            Tocolcodecfilter (New Objectserializationcodecfactory ()));                } connector.getfilterchain (). AddLast ("Logger", New Loggingfilter ());                Connector.sethandler (new Clientsessionhandler (values));            Iosession session; for (;;)                            {try {connectfuture future = Connector.connect (New inetsocketaddress (                    HOSTNAME, PORT));                    Future.awaituninterruptibly ();                    Session = Future.getsession ();               Break } catch (Runtimeioexception e) {System.err.println ("Failed to COnnect. ");                    E.printstacktrace ();                Thread.Sleep (5000); }}//Wait until the summation is do Session.getclosefuture (). awaituninterruptibly (                        );        Connector.dispose (); }    }

UDP example does not write, if necessary, to visit the Apache official website.

Http://mina.apache.org/mina-project/userguide/ch2-basics/sample-udp-client.html

The above is the Apache Mina study Note (2)-The basic content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!

  • 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.