The his experiment of Apache Mina's actual combat

Source: Internet
Author: User
Tags getmessage sessions throwable

This article link: http://blog.csdn.net/kongxx/article/details/7520259

The Apache Mina is a network application framework that is used to build high-performance and highly scalable applications, providing a unified set of event-driven asynchronous APIs built on Java NIO.

For the understanding of the Mina framework, several of the official Mina's articles are to be seen, 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 of the main components are as follows:

I/O Service-Used to process I/O flows, accept client-side connection requests for server-side Ioacceptor implementation classes, and establish connections to the server side for client-side Ioconnector implementation classes.

I/O filter Chain-used to filter or transform data. For both the server end and the client side are implementation classes for the Iofilter interface, and Mina has built many implementations of the Iofilter interface. You can refer to the official documentation.

I/O Handler-classes that are used to handle real business logic. The implementation class for the Iohandler interface for both the server side and the client side is usually required to write on its own.


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

For the server side:

1. Create I/O service-This is the creation of the Ioacceptor class listening port.

2. Create I/O Filter Chain-here is to tell the use of those iofilter.
3. Create I/O Handler-own business logic.

For the client side:

1. Create I/O service-This is the creation of the Ioconnector class to establish a connection to the server side.

2. Create I/O Filter Chain-here is to tell the use of those iofilter.

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

Here's an example to see how Mina works. Since most applications are based on TCP/IP applications, this is no longer said to be UDP/IP.

Here I use Maven to create a simple Java application, and take a step in the Official Handbook of MAVEN. Here's just a list of the Maven profiles I used, pom.xml for the following and subsequent articles. The contents of the specific Pom.xml document are as follows:

<project xmlns= "http://maven.apache.org/POM/4.0.0" xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xsi: schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd" > <modelversion >4.0.0</modelVersion> <groupId>com.google.code.garbagecan.minastudy</groupId> < Artifactid>minastudy</artifactid> <packaging>jar</packaging> <version>1.0-snapshot </version> <name>minastudy</name> <url>http://maven.apache.org</url> < dependencies> <dependency> <groupId>org.apache.mina</groupId> <artifactid>mina-core&lt ;/artifactid> <version>2.0.4</version> </dependency> <dependency> <groupid>org. Apache.mina</groupid> <artifactId>mina-filter-compression</artifactId> <version>2.0.4 </version> </dependency> <dependency> <groupid>org.slf4j</groupid> <artifactId>slf4j-api</artifactId> <version>1.3.0</version> </dependency>
			<dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>1.3.0</version> </dependency> </dependencies> </project>
First look at the server-side code

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 Exce ption {} @Override public void sessionopened (Iosession session) throws Exception {} @Override Pub LIC void Sessionclosed (iosession session) throws Exception {} @Override public void Sessionidle (Iosession Sessi On, idlestatus status) throws Exception {} @Override public void Exceptioncaught (iosession session, Throwable C
				Ause) throws Exception {Logger.error (Cause.getmessage (), cause);
			Session.close (TRUE); @Override public void messagereceived (iosession sessions, Object message) throws Exception {Logger.info ("rece
				Ived message "+ message);
			Session.write (message); @Override public void Messagesent (iosession sessions, Object message) throws Exception {logger.info ("Sent mes
			Sage "+ message);
		
		}
		}); try {acceptor.bind (new InetsocketAddress (10000));
		catch (IOException ex) {Logger.error (Ex.getmessage (), ex); }
	}
}
1. First create the I/O Service, where the Niosocketacceptor class is used to create a ioacceptor instance.

2. Create I/O Filter Chain, where two iofilter are used, one is loggingfilter to log and print event messages, and the other is Protocolcodecfilter instances to encode data. This is actually encoding the passed data into text.

3. Create I/O Handler, do not be afraid, it seems that the code is more, in fact, is a implementation of the Iohandler interface of the subclass, you need to implement some of these methods, here a lot of methods, but here I only realize the messagesent, Messagereceived and Exceptioncaught methods.

4. Finally, let the Ioacceptor class instance bind the port to implement listening.

Let's look at the client side of the 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 (New Textlinecodecfactory (Charset.forname) ("
		
		UTF-8 "))); Connector.sethandler (New Iohandleradapter () {@Override public void sessioncreated (iosession session) throws exc Eption {} @Override public void sessionopened (Iosession sessions) throws Exception {for (int i = 0; i < 10;
				i++) {session.write ("Hello user_" + i);
			} session.write ("Bye"); @Override public void sessionclosed (Iosession sessions) throws Exception {} @Override public void Sessi OnIdle (iosession session, Idlestatus status) throws Exception {} @Override public void Exceptioncaught (Iosessio
				n Session, Throwable cause) throws Exception {Logger.error (Cause.getmessage (), cause);
			Session.close (TRUE); @Override public void messagereceived (iosession sessions, Object message) throws Exception {Logger.info ("rece Ived message "+ message);
				if (message.tostring (). Equalsignorecase ("Bye")) {Session.close (true); @Override public void Messagesent (iosession sessions, Object message) throws Exception {Logger.info ("Sen
			T 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 I/O Service, where the Niosocketconnector class is used to create a Ioconnector instance and set the connection timeout to 10 seconds.

2. Create I/O Filter Chain, and the server side also set up two Iofilter, one is loggingfilter to log and print event messages, and the other is Protocolcodecfilter instance to encode data, This is actually encoding the passed data into text.

3. Create I/O Handler, do not be afraid, it seems that the code is more, in fact, is a implementation of the Iohandler interface subclass, and the realization of their own sessionopened,messagesent, Messagereceived and Exceptioncaught methods. The Sessionopened method is implemented to send messages to the server side after the connection is established. Also look at the Messagereceived method implementation, which closes the session after receiving the server-side message. This allows the client program to eventually exit.

4. Finally, the Ioconnector instance class connects to the remote server.

The following test the above program, first run the MyServer class, and then run the MyClient class, you can respectively at their respective terminals see the event log and send/Receive messages.

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.