Use Apache Mina to develop high-performance network applications

Source: Internet
Author: User

Apache Mina (Multipurpose infrastructure for network applications) is a newer project in Apache, which provides a very convenient framework for developing high-performance and high-availability network applications. The currently released Mina version supports TCP/UDP application development and serial communication programs based on Java NiO Technology (only available in the latest preview version ), functions supported by Mina are also being expanded.

Currently, Mina software is used, including Apache Directory Project, asyncweb, amqp (Advanced Message Queuing protocol), red5 server (Macromedia Flash Media rtmp), objectradius, and openfire.

This article introduces the basic architecture of Mina through a simple greeting program helloserver, and demonstrates how to use Mina to develop network applications.

Environment preparation

  1. Download the latest Mina version from the official website at http://mina.apache.org/downloads.html. Before downloading the SDK, we will first introduce two Mina versions: 1.0.x is suitable for running the jdk1.4 environment, 1.1.x is suitable for the jdk1.5 version, and jdk1.5 is required for both compiling environments. Jdk1.5 is already very common, this article uses version 1.1.5 of Mina, the files needed for compilation and running are mina-core-1.1.5.jar.
  2. Download the Mina dependency package slf4j. Mina uses this project as the log information output, and Mina itself does not come with this project package, please go to the http://www.slf4j.org/download.html address to download the slf4j package, slf4j project Decompression has a lot of files, in this example, only the slf4j-api-1.4.3.jar and slf4j-simple-1.4.3.jar jar files are needed. Without these two files, the org/slf4j/loggerfactory class will not be found when the example program is started.
  3. Of course, JDK 1.5 or later must be installed on the machine.
  4. It is recommended that you select a handy Java development environment such as eclipse or netbeans to facilitate coding and debugging, although our minimum requirement is just a simple text editor.

Back to Top

Write and execute code

  1. Compile the code helloserver. Java as follows:
Package demo. mina. echo; import Java. io. ioexception; import java.net. inetsocketaddress; import Org. apache. mina. common. *; import Org. apache. mina. transport. socket. NIO. *; import Org. apache. mina. filter. codec. protocolcodecfilter; import Org. apache. mina. filter. codec. textline. textlinecodecfactory;/*** helloserver demo program * @ author liudong (http://www.dlog.cn/javayou) */Public class helloserver {Private Static final intPort= 8080;/*** @ Param ARGs * @ throws ioexception */public static void main (string [] ARGs) throws ioexception {ioacceptor acceptor = new socketacceptor (); ioacceptorconfig Config = new socketacceptorconfig (); defaultiofilterchainbuilder chain = config. getfilterchain (); // use a string to encode the chain. addlast ("codec", new protocolcodecfilter (New textlinecodecfactory (); // start helloserver acceptor. BIND (New inetsocketaddress (Port), New hellohandler (), config); system.Out. Println ("helloserver started on port" +Port);}} /*** Helloserver processing logic * @ author liudong */class hellohandler extends iohandleradapter {/*** triggered when an exception occurs */@ override public void exceptioncaught (iosession SSN, throwable cause) {cause. printstacktrace (); SSN. close ();}/*** triggered when a new connection exists */@ override public void sessionopened (iosession SSN) throws exception {system.Out. Println ("session open for" + SSN. getremoteaddress ();}/*** triggered when the connection is closed */@ override public void sessionclosed (iosession SSN) throws exception {system.Out. Println ("session closed from" + SSN. getremoteaddress ();}/*** receives a message from the client */Public void messagereceived (iosession SSN, object MSG) throws exception {string IP = SSN. getremoteaddress (). tostring (); system.Out. Println ("==> message from" + IP + ":" + MSG); SSN. Write ("hello" + MSG );}}


  1. Compile and execute

First, you don't need to try to understand the specific meaning of each line of code. Compile helloserver with your handy compiler. java. If an error is reported, check whether the three jar files mentioned above have been added to the class path. If everything goes well, you can start the helloserver program, and the prompt is:HelloServer started on port 8080 Indicates that the instance is successfully started. If the instance fails to be started, the class is not found or the port is occupied. If the port is in use, change itPORT Compile and start the constant value again.

  1. Test Server

Open the command line window, enter Telnet localhost 8080, enter your English name or other messy characters, and then press enter to see how the newly started service responds. My response is as follows:

HelloServer started on port 8080 session open for /127.0.0.1:3023 ===> Message From /127.0.0.1:3023 :hello ===> Message From /127.0.0.1:3023 :hello ===> Message From /127.0.0.1:3023 :liudong ===> Message From /127.0.0.1:3023 :Winter Lau 


Okay, everything works. Congratulations! Your first useMINA The developed network program has been successfully run.

Back to Top

Description of the Mina basic class

Before introducing the architecture, you must first understand Several Interfaces:

Ioaccepter is equivalent to a server in a network application.

Ioconnector is equivalent to a client

Iosession: A connection instance from the current client to the server

Iohandler business processing logic

Iofilter is used to suspend communication layer interfaces and business layer interfaces.

Back to Top

Basic architecture of Mina

YesMINA Architecture diagram,


Figure 1: Architecture of Mina
 

In the blockchain in the figure, ioservice is the entry of the application, which is equivalent to ioaccepter in the previous Code. ioaccepter is an extended interface of ioservice. The ioservice interface can be used to add multiple iofilters. These iofilters comply with the responsibility chain mode and are called by the ioprocessor thread. Ioaccepter also provides an interface for binding a communication port and unbinding an ioservice interface. In the above example, we use ioaccepter as follows:

IoAcceptor acceptor = new SocketAcceptor(); 


This is equivalent to using the socket communication method as the service access. The current version of Mina also provides the datagetaccepter and the data packet communication-based mongoramaccepter and the vmpipeaccepter Based on pipeline communication. In addition, it also includes the serial communication access method. Currently, the access method based on serial communication is provided in the latest test version of Mina. You can also implement the ioservice interface to use your own communication method.

The rightmost end is iohandler, which is the business processing module. It is equivalent to the hellohandler class in the previous example. In the business processing class, you don't need to care about the actual communication details, just process the information transmitted by the client. Writing a handler class is the focus of developing network applications using Mina, which is equivalent to the fact that Mina has helped you deal with all the communication details. To simplify the handler class, Mina provides the iohandleradapter class, which only implements the iohandler interface, but does not process it.

An iohandler interface has the following methods (from the Mina API documentation ):

VoidPredictioncaught(Iosession session, throwable cause)
This method is triggered when exceptions thrown by other methods in the interface are not captured.
VoidMessagereceived(Iosession session, object message)
This method is triggered when the client request information is received.
VoidMessagesent(Iosession session, object message)
This method is triggered when the information has been sent to the client.
VoidSessionclosed(Iosession session)
Triggered when the connection is closed, such as unexpected exit of the client program.
VoidSessioncreated(Iosession session)
This method is triggered when a new client is connected.
VoidSessionidle(Iosession session, idlestatus status)
This method is triggered when the connection is idle.
VoidSessionopened(Iosession session)
This method is triggered when the connection is enabled. Generally, this method and sessioncreated are both triggered.


As mentioned above, ioservice is responsible for underlying communication access, while iohandler is responsible for business processing. So what is the use of iofilter in the Mina architecture diagram? The answer is what you want to do. However, it is necessary to use ioservice as a bridge between ioservice and iohandler. The most important method in the iohandler interface is messagereceived. The second parameter of this method is an object-type message. The object is the basis of all Java objects, who decides the type of the message? The answer is in this iofilter. In the previous example, we added an iofilter that is new protocolcodecfilter (New textlinecodecfactory ()), the function of this filter is to convert the information input from the client into a line of text and pass it to iohandler. Therefore, we can directly convert the MSG object to a string object in messagereceived.

If we do not provide any filters, the second parameter type in the messagereceived method is a byte buffer, and the corresponding class is org. Apache. Mina. Common. bytebuffer. Although you can also put the parsing client information in iohandler, this is not a recommended practice, so that the original clear model is blurred and the iohandler is not just a business process, it must also act as a task for protocol parsing.

Mina has some common filters, such as loggingfilter, blacklistfilter, compressionfilter, and sslfilter.

Back to Top

Others

Mina is not only used to develop network server applications, but can also use ioconnector to connect to a variety of network service programs.

Through the helloserver example in this article, we are amazed at how convenient Mina can bring, while we have to be proud of its outstanding performance, it is said that the performance of the Mina server program has approached the network service developed in C/C ++ language. As an entry to Mina, performance issues are not covered in this article.

In addition, there are many examples that are much better than helloserver included in the Mina compressed package. Through these examples, we can further understand and master Mina.


References

  • Http://mina.apache.orgMINA Official Website

  • Http://mina.apache.org/features.htmlyou can refer to more features about Mina here
  • Http://mina.apache.org/testimonials.htmllet's take a look at others' comments on Mina's http://asyncweb.safehaus.org/use the high-performance WEB server developed by Mina

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.