Apache MINA practices (1)

Source: Internet
Author: User

Apache MINA is a network application framework used to build high-performance and high-scalability applications. It provides a unified set of event-driven asynchronous APIs built on Java NIO.

To understand the MINA framework, several official articles of MINA must be viewed as follows:

* Application Architecture http://mina.apache.org/mina-based-application-architecture.html

* Server Architecture http://mina.apache.org/server-architecture.html

* Client Architecture http://mina.apache.org/client-architecture.html

The main components are as follows:

I/O Service-it is used to process I/O streams. For the implementation class of IOAcceptor on the Server side, it accepts connection requests from the Client side, the Client is the implementation class of IoConnector to establish a connection to the Server.

I/O Filter Chain-used to Filter or convert data. Both the Server and Client are implementation classes of the IoFilter interface. MINA has many built-in implementation classes of the IoFilter interface. For more information, see the official documentation.

I/O Handler-class used to process real business logic. Both the Server and Client are implementation classes of the IoHandler interface, which usually needs to be compiled by yourself.

Because both the Server and Client are based on the above three components, both the Server and Client programming have a similar code structure.

For the Server side:

1. Create an I/O service. Here, create an IOAcceptor listener port.

2. Create an I/O Filter Chain-here we will tell you to use those iofilters.

3. Create an I/O Handler-your own business logic.

For the Client:

1. Create an I/O service-create an IOConnector class to establish a connection to the Server.

2. Create an I/O Filter Chain-here we will tell you to use those iofilters.

3. Create an I/O Handler-your own business logic.

The following example shows how MINA works. Most applications are based on TCP/IP, so UDP/IP is not mentioned here.

Here I used Maven to create a simple java application. For detailed steps, see the official Maven manual. Here we will only list the maven configuration file pom. xml that I use for the convenience of the following and subsequent articles. The content of the pom. xml file is as follows:

 
  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
  2.     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">  
  3.     <modelVersion>4.0.0</modelVersion>  
  4.     <groupId>com.google.code.garbagecan.minastudy</groupId>  
  5.     <artifactId>minastudy</artifactId>  
  6.     <packaging>jar</packaging>  
  7.     <version>1.0-SNAPSHOT</version>  
  8.     <name>minastudy</name>  
  9.     <url>http://maven.apache.org</url>  
  10.     <dependencies>  
  11.         <dependency>  
  12.             <groupId>org.apache.mina</groupId>  
  13.             <artifactId>mina-core</artifactId>  
  14.             <version>2.0.4</version>  
  15.         </dependency>  
  16.         <dependency>  
  17.             <groupId>org.apache.mina</groupId>  
  18.             <artifactId>mina-filter-compression</artifactId>  
  19.             <version>2.0.4</version>  
  20.         </dependency>  
  21.         <dependency>  
  22.             <groupId>org.slf4j</groupId>  
  23.             <artifactId>slf4j-api</artifactId>  
  24.             <version>1.3.0</version>  
  25.         </dependency>  
  26.         <dependency>  
  27.             <groupId>org.slf4j</groupId>  
  28.             <artifactId>slf4j-log4j12</artifactId>  
  29.             <version>1.3.0</version>  
  30.         </dependency>  
  31.     </dependencies>  
  32. </project> 

First, let's look at the Server code.

 
  1. package com.google.code.garbagecan.minastudy.sample1;  
  2.  
  3. import java.io.IOException;  
  4. import java.net.InetSocketAddress;  
  5. import java.nio.charset.Charset;  
  6.  
  7. import org.apache.mina.core.service.IoAcceptor;  
  8. import org.apache.mina.core.service.IoHandlerAdapter;  
  9. import org.apache.mina.core.session.IdleStatus;  
  10. import org.apache.mina.core.session.IoSession;  
  11. import org.apache.mina.filter.codec.ProtocolCodecFilter;  
  12. import org.apache.mina.filter.codec.textline.TextLineCodecFactory;  
  13. import org.apache.mina.filter.logging.LoggingFilter;  
  14. import org.apache.mina.transport.socket.nio.NioSocketAcceptor;  
  15. import org.slf4j.Logger;  
  16. import org.slf4j.LoggerFactory;  
  17.  
  18. public class MyServer {  
  19.       
  20.     private static final Logger logger = LoggerFactory.getLogger(MyServer.class);  
  21.       
  22.     public static void main(String[] args) {  
  23.         IoAcceptor acceptor = new NioSocketAcceptor();  
  24.  
  25.         acceptor.getFilterChain().addLast("logger", new LoggingFilter());  
  26.         acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));  
  27.  
  28.         acceptor.setHandler(new IoHandlerAdapter() {  
  29.               
  30.             @Override 
  31.             public void sessionCreated(IoSession session) throws Exception {  
  32.             }  
  33.               
  34.             @Override 
  35.             public void sessionOpened(IoSession session) throws Exception {  
  36.             }  
  37.  
  38.             @Override 
  39.             public void sessionClosed(IoSession session) throws Exception {  
  40.             }  
  41.  
  42.             @Override 
  43.             public void sessionIdle(IoSession session, IdleStatus status) throws Exception {  
  44.             }  
  45.  
  46.             @Override 
  47.             public void exceptionCaught(IoSession session, Throwable cause) throws Exception {  
  48.                 logger.error(cause.getMessage(), cause);  
  49.                 session.close(true);  
  50.             }  
  51.  
  52.             @Override 
  53.             public void messageReceived(IoSession session, Object message) throws Exception {  
  54.                 logger.info("Received message " + message);  
  55.                 session.write(message);  
  56.             }  
  57.  
  58.             @Override 
  59.             public void messageSent(IoSession session, Object message) throws Exception {  
  60.                 logger.info("Sent message " + message);  
  61.             }  
  62.         });  
  63.           
  64.         try {  
  65.             acceptor.bind(new InetSocketAddress(10000));  
  66.         } catch (IOException ex) {  
  67.             logger.error(ex.getMessage(), ex);  
  68.         }  
  69.     }  
  70. } 

1. First create an I/O Service. Here we use the NioSocketAcceptor class to create an IoAcceptor instance.

2. create an I/O Filter Chain. Two iofilters are used here. One is LoggingFilter used to record logs and print event messages, and the other is ProtocolCodecFilter instance used to encode data, here we actually encode the transmitted data into text.

3. do not be afraid to create I/O Handler. It seems that there are many codes. It is actually a subclass that implements the IoHandler interface. You need to implement some of these methods. Here there are many methods, however, here I only implement the messageSent, messageReceived, and predictioncaught methods.

4. Finally, bind the IoAcceptor class instance to a port for listening.


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.