Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What's the use of Apache's MINA?

2025-03-04 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article will explain in detail what is the use of MINA about Apache. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Apache's MINA is a web application framework used to build high-performance and highly scalable applications. It provides a unified set of event-driven asynchronous API based on Java NIO.

For an understanding of the MINA framework, several official MINA articles are required, 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

Several major components are as follows:

I Service O Service-it is used to handle the IOAcceptor O stream. For the server-side implementation class, the client-side implementation class accepts connection requests from the client side, and for the client-side implementation class, the client-side implementation class is IoConnector to establish a connection to the server side.

I am O Filter Chain-used to filter or convert data. Both the server side and the client side are the implementation classes of the IoFilter interface. MINA itself has built a lot of implementation classes of the IoFilter interface. You can refer to the official documentation for details.

I use O Handler-the class used to handle real business logic. For both the server side and the client side, it is the implementation class of the IoHandler interface, which usually needs to be written by yourself.

Because both the server side and the client side are based on the above three components, there is a similar code structure for both server and client side programming.

For the server side:

1. Create the IOAcceptor O service-this is where you create the listening port for the IOAcceptor class.

two。 Create the IoFilter O Filter Chain-this is where the IoFilter is told to use.

3. Create your own business logic, I am O Handler.

For the client side:

1. Create the IOConnector O service-this is where the IOConnector class is created to establish a connection to the server side.

two。 Create the IoFilter O Filter Chain-this is where the IoFilter is told to use.

3. Create your own business logic, I am O Handler.

Let's use an example to see how MINA works. Since most applications are based on TCP/IP, we will not talk about UDP/IP here.

Here I use Maven to create a simple java application, please refer to Maven's official manual for specific steps. Here is just a list of the maven configuration file I used, pom.xml, for the convenience of the following and subsequent articles. The details of the pom.xml file are as follows:

4.0.0 com.google.code.garbagecan.minastudy minastudy jar 1.0-SNAPSHOT minastudy http://maven.apache.org org.apache.mina mina-core 2.0.4 org.apache.mina mina-filter-compression 2.0.4 org.slf4j slf4j-api 1.3.0 org.slf4j slf4j-log4j12 1.3.0

First, let's take a look at the code on the server side.

Package com.google.code.garbagecan.minastudy.sample1; 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.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; 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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyServer {private static final Logger logger = LoggerFactory.getLogger (MyServer.class); public static void main (String [] args) {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 IoHandlerAdapter () {@ Override public void sessionCreated (IoSession session) throws Exception {} @ Override public void sessionOpened (IoSession session) throws Exception {} @ Override public void sessionClosed (IoSession session) throws Exception {} @ Override public void sessionIdle (IoSession session IdleStatus status) throws Exception {} @ Override public void exceptionCaught (IoSession session, Throwable cause) throws Exception {logger.error (cause.getMessage (), cause) Session.close (true);} @ Override public void messageReceived (IoSession session, Object message) throws Exception {logger.info ("Received message" + message); session.write (message) } @ Override public void messageSent (IoSession session, Object message) throws Exception {logger.info ("Sent message" + message);}}); try {acceptor.bind (new InetSocketAddress (10000)) } catch (IOException ex) {logger.error (ex.getMessage (), ex);}

1. The first step is to create the NioSocketAcceptor O Service, where the NioSocketAcceptor class is used to create an instance of IoAcceptor.

two。 To create the IoFilter O Filter Chain, two CPUs are used, one is LoggingFilter to log and print event messages, the other is ProtocolCodecFilter instance to encode the data, which is actually encoding the passed data into text.

3. Don't be afraid to create the IoHandler O Handler. It looks like a lot of code, but it is actually a subclass that implements the IoHandler interface. You need to implement some of these methods. There are many methods here, but I only implement the messageSent,messageReceived and exceptionCaught methods here.

4. * allows the IoAcceptor class instance to bind the port to listen.

Let's take a look at the client code.

Package com.google.code.garbagecan.minastudy.sample1; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.service.IoConnector; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; 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.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class MyClient {private static final Logger logger = LoggerFactory.getLogger (MyClient.class); public static void main (String [] args) {IoConnector connector = new NioSocketConnector () Connector.setConnectTimeoutMillis (10 * 1000); connector.getFilterChain (). AddLast ("logger", new LoggingFilter ()); connector.getFilterChain () .addLast ("codec", new ProtocolCodecFilter (Charset.forName ("UTF-8") Connector.setHandler (new IoHandlerAdapter () {@ Override public void sessionCreated (IoSession session) throws Exception {} @ Override public void sessionOpened (IoSession session) throws Exception {for (int I = 0; I < 10) Session.write +) {session.write ("Hello user_" + I);} session.write ("Bye") } @ Override public void sessionClosed (IoSession session) throws Exception {} @ Override public void sessionIdle (IoSession session, IdleStatus status) throws Exception {} @ Override public void exceptionCaught (IoSession session, Throwable cause) throws Exception {logger.error (cause.getMessage (), cause) Session.close (true);} @ Override public void messageReceived (IoSession session, Object message) throws Exception {logger.info ("Received message" + message); if (message.toString (). EqualsIgnoreCase ("Bye")) {session.close (true) } @ Override public void messageSent (IoSession session, Object message) throws Exception {logger.info ("Sent message" + message);}}); IoSession session = null; try {ConnectFuture future = connector.connect (new InetSocketAddress ("localhost", 10000)) Future.awaitUninterruptibly (); session = future.getSession ();} catch (RuntimeIoException e) {logger.error (e.getMessage (), e);} session.getCloseFuture (). AwaitUninterruptibly (); connector.dispose ();}}

1. First create the NioSocketConnector O Service, where the NioSocketConnector class is used to create an instance of IoConnector and set the connection timeout to 10 seconds.

two。 To create the IoFilter O Filter Chain, two CPUs are also set up on the server side, one is used to log and print event messages, and the other is the ProtocolCodecFilter instance used to encode the data. Here, the transmitted data is encoded into text.

3. Don't be afraid to create IoHandler O Handler. It looks like a lot of code, but it is actually a subclass that implements the IoHandler interface and implements the sessionOpened,messageSent,messageReceived and exceptionCaught methods yourself. The sessionOpened method is implemented to send a message to the server side after the connection is established. Also take a look at the messageReceived method implementation, which closes the session after receiving a message from the server side. So that the Client program can finally exit.

4. * is the Server where the IoConnector instance class connects to the remote end.

Let's test the above program, first run the MyServer class, and then run the MyClient class, and you can see the event log and the sent / received messages on the respective terminals.

This is the end of this article on "what is the use of Apache's MINA?". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report