The actual object transmission of the Apache Mina

Source: Internet
Author: User
Tags getmessage serialization sessions throwable stringbuffer

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

Using the Apache Mina to pass objects is very easy for Mina, and is a common application in Java network programming. In fact, for Mina passing object, if you read the previous article, as long as a little change in it can implement object delivery, but here, considering the integrity of the example, or give all the code examples.

First look at two of the Java objects used to pass the Myrequestobject and Myresponseobject, it is simple to implement the serializable interface just.

Package com.google.code.garbagecan.minastudy.sample3;

Import java.io.Serializable;

	public class Myrequestobject implements Serializable {private static final long serialversionuid = 1L;
	
	private String name;

	private String value;
		Public Myrequestobject (string name, String value) {this.name = name;
	This.value = value;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public String GetValue () {return value;
	public void SetValue (String value) {this.value = value;
		@Override public String toString () {stringbuffer sb = new StringBuffer ();
		Sb.append ("Request [Name:" + name + ", Value:" + value + "]");
	return sb.tostring ();

}} package Com.google.code.garbagecan.minastudy.sample3;

Import java.io.Serializable;

	public class Myresponseobject implements Serializable {private static final long serialversionuid = 1L;
	
	private String name;

	private String value; Public MyresponseobjecT (string name, String value) {this.name = name;
	This.value = value;
	Public String GetName () {return name;
	public void SetName (String name) {this.name = name;
	Public String GetValue () {return value;
	public void SetValue (String value) {this.value = value;
		@Override public String toString () {stringbuffer sb = new StringBuffer ();
		Sb.append ("Response [Name:" + name + ", Value:" + value + "]");
	return sb.tostring ();
 }
}
Look at the server-side code

Package com.google.code.garbagecan.minastudy.sample3;
Import java.io.IOException;

Import java.net.InetSocketAddress;
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.serialization.ObjectSerializationCodecFactory;
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 ObjectserializationcodecfactorY ())); 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);
				Myrequestobject MYREQOJB = (myrequestobject) message;
				Myresponseobject myresobj = new Myresponseobject (Myreqojb.getname (), Myreqojb.getvalue ());
			Session.write (Myresobj); @Override public void Messagesent (iosession sessions, Object message)Throws Exception {logger.info ("Sent" + 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, which uses two iofilter, one is loggingfilter to log and print event messages, and the other is Protocolcodecfilter instance to encode data. This uses the Objectserializationcodecfactory class to serialize or deserialize the data into Java objects.

3. Create I/O Handler, here mainly look at the Messagereceived method, its total received Myrequestobject object, and then sent a Myresponseobject object to the client side.

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


Look at the client side of the code

Package com.google.code.garbagecan.minastudy.sample3;

Import java.net.InetSocketAddress;
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.serialization.ObjectSerializationCodecFactory;
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 Objectserializationcodecfactory ()); Connector.sethandler (New Iohandleradapter () {@Override public void sessioncreated (iosession session) throws exc  Eption {} @Override public void sessionopened (Iosession session) throws Exception {Myrequestobject myobj =
				New Myrequestobject (' My Name ', ' my value ');
			Session.write (myobj); @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 {Myresponseobject
				Myresobj = (myresponseobject) message; Logger.info ("REceived "+ myresobj);
			Session.close (TRUE);  @Override public void Messagesent (iosession sessions, Object message) throws Exception {logger.info ("Sent" +
			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, The Objectserializationcodecfactory class is also used to serialize or deserialize data into Java objects.

3. Create I/O Handler, mainly look at the sessionopened method, where the Myrequestobject object was sent in the session-building event, and then the Myresponseobject object was accepted in the Messagereceived method.

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 at their respective terminals see the event log and send/Receive objects.






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.