Initial contact with Apache Mina server

Source: Internet
Author: User
Tags stub

Apache Mina Server is a network communication application framework, mainly for the communication framework based on the TCP/IP,UDP/IP protocol stack, Mina can help to quickly develop high-performance, highly scalable network communications applications, Mina provides event-driven, asynchronous operation of the programming model.


Mina also provides a server-side, client-side encapsulation of network traffic, regardless of which end, Mina is in the following position throughout the structure:


Visible Mima APIs Isolate real network communications from civilized applications, and you only need to care about the data you send, receive, and your business logic.

Again, no matter which end, Mina's execution process is as follows:



1 Ioservice: This interface is responsible for the establishment of sockets on a thread, has its own selector, and listens for new connections to be built.

2 Ioprocessor: This interface is responsible for checking whether data is read or written on the channel on another thread, which means it has its own selector.

3 Iofilter: This interface defines a set of interceptors, which can include log output, blacklist filtering, data encoding, decoding, and so on, encoding, decoding is the most important, but also you want to use Mina when the most concerned about the place.

4 Iohandler: This interface is responsible for writing business logic, that is, where to receive and send data.


Example: Simple TCPServer

/** * TCP SERVER * @function: * @author: JY * @company: Wanli network * @date: 2011-7-23/public class MyServer {
	public static ioacceptor acceptor = null; /** * @param args * @throws ioexception/public static void main (string[] args) throws IOException {acceptor
		= new Niosocketacceptor (); Acceptor.getsessionconfig (). Setreadbuffersize (2048);//Read buffer size acceptor.getsessionconfig (). Setidletime (
		Idlestatus.both_idle, 10);//Enter idle time Acceptor.getsessionconfig (). Setusereadoperation (true);//Data readable Acceptor.getsessionconfig (). Setwritetimeout (30);//write timeout/character filter acceptor.getfilterchain (). AddLast ("CODEC1", new
		Protocolcodecfilter (New Textlinecodecfactory ());
		Acceptor.getfilterchain (). AddLast ("Myiofilter", New Referencecountingfilter (New Myiofilter ()); Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Cmsssipccodecfactory (Charset.forname) ("
		UTF-8 "))); Acceptor.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New FlightcodecfactOry (Charset.forname ("UTF-8")));
		
		Binding business logic Acceptor.sethandler (New Myiohandler ());
 Acceptor.bind (New Inetsocketaddress (9123));//Listener port number}}

Simple client:

/**
 * @function: 
 * @author   : JY
 * @company  : Wanli Network
 * @date     : 2011-7-24
/Public Class MyClient {

	/**
	 * @param args
	 * @throws ioexception * * Public
	static void Main (string[) args) throws IOException {
		Ioconnector conneector = new Niosocketconnector ();
		Conneector.setconnecttimeoutmillis (30000);
		Conneector.getfilterchain (). AddLast ("Codec1", New Protocolcodecfilter (New Textlinecodecfactory ());
		Conneector.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Cmsssipccodecfactory (Charset.forname) (" UTF-8 ")));
		Conneector.getfilterchain (). AddLast ("Codec", new Protocolcodecfilter (New Flightcodecfactory (Charset.forname) (" UTF-8 ")));
		Conneector.getsessionconfig (). Setusereadoperation (true);
		Conneector.sethandler (New Myclienthandler ());
		Conneector.connect (New inetsocketaddress ("localhost", 9123));
	}



Note: Both TCP server and TCP client must bind Hanndler, otherwise an exception will be thrown.

Server Handler:myiohandler

/** * @function: * @author: JY * @company: Wanli network * @date: 2011-7-23/public class Myiohandler extends Iohand

	Leradapter {Private final static Logger log = Loggerfactory.getlogger (Myiohandler.class);
	 /** * The method that is invoked when a message is received, which is the method used to receive information.
	 * message is generally a iobuffer class, if you use a protocol codec, you can cast to the type you need.
	 * The protocol codec is usually used.
	 * For example: using the Textlinecodecfactory protocol codec, you can cast the message to a string type.
		* * @Override public void messagereceived (iosession sessions, Object message) {Flight SMS = (Flight) message;
		String SMS = (string) message;
		Log.info ("The message recevied is [+ SMS +]");
		Session.write (New Java.util.Date ());
		Session.close (TRUE);
		
Session.write (Session.getattribute ("Test")); if (Str.equals ("All")) {////sendall ()///////if (Str.endswith ("Quit")) {//Session.close (TRUE);//Retur
N
}///**//* This method is invoked when a session object is created.
* For a TCP connection, the connection is invoked when it is accepted, but be aware that the TCP connection is not established at this point, that is, when the connected object iosession is created//*, callback this method. * For UDP, callback this method when a packet is received, because uThe DP is not connected. *//@Override//public void sessioncreated (iosession session) {//Session.write ("welcome!\r");/////** * Process The order itself occurs when an exception callback, generally shut down iosession/@Override public void Exceptioncaught (iosession session, Throwable able) throws Exceptio
	n {able.printstacktrace ();
//////**//* This method is invoked when a message is sent successfully.
* Note that this is not the way to send a message when it is sent successfully. *//@Override//public void Messagesent (Iosession arg0, Object arg1) throws Exception {///TODO auto-generated
Method stub//////////////* For TCP, this is invoked when the connection is closed/**.
* For UDP, the Iosession Close () method is called to destroy this method. 
*//@Override//public void sessionclosed (Iosession arg0) throws Exception {////TODO auto-generated method stub
//////**//* Call when Iosession Channel is idle.
* This method is never invoked for the UDP protocol. *//@Override//public void Sessionidle (Iosession arg0, Idlestatus arg1) throws Exception {///TODO Auto-genera
Ted method Stub//////////**///* When the connection is opened, it is always invoked after the sessioncreated () methods. * FORTCP, which is invoked after the connection is established, where it can perform some authentication, send data operations, and so on. * For UDP, this method does not differ from sessioncreated (), but is followed by execution.
If you send some data every once in a while, the//* sessioncreated () method is invoked only the first time, but the sessionopened () method is invoked each time. 
*//@Override//public void sessionopened (Iosession arg0) throws Exception {////TODO auto-generated method stub //		
//	}
}

Client Hanlder:myclienthandler

/**
 * @function: 
 * @author   : JY
 * @company  : Wanli Network
 * @date     : 2011-7-24
/Public Class Myclienthandler extends Iohandleradapter {
	/* (non-javadoc)
	 * @see Org.apache.mina.core.service.iohandler#sessioncreated (org.apache.mina.core.session.IoSession)
	 * *
	Override public
	void Sessioncreated (Iosession session) throws Exception {
//		smsobject SMS = new Smsobject ();		Sms.setsender ("13721047855");		sms.setreceiver ("15855533814");		sms.setmessage ("Hello MiNa");		session.write (SMS);		Flight Flight = new Flight ();		flight.setfirstcity ("SHA");		flight.setfirstday ("2011-07-28");		Flight.setflightway ("dobuble");		flight.setsecondcity ("BJs");		flight.setsecondday ("2011-07-29");		flight.setthirdcity ("SHA");		session.write (flight);
		After you have established the custom data encode, decode, you can send the object.
		
		session.write ("Hello 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.