Link: http://blog.csdn.net/kongxx/article/details/7520599
Using Apache Mina to pass objects is very easy for Mina, and it is also a common application in Java Network Programming. In fact, for objects passed by Mina, if you have read the previous article, you only need to make a few changes in it to implement object transfer. However, considering the integrity of the example, we still provide all the code examples.
First, let's take a look at two Java objects myrequestobject and myresponseobject to be passed. It's easy to just implement the serializable interface.
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;}@Overridepublic 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;}@Overridepublic String toString() {StringBuffer sb = new StringBuffer();sb.append("Response [name: " + name + ", value: " + value + "]");return sb.toString();}}
Check the server 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() {@Overridepublic void sessionCreated(IoSession session) throws Exception {}@Overridepublic void sessionOpened(IoSession session) throws Exception {}@Overridepublic void sessionClosed(IoSession session) throws Exception {}@Overridepublic void sessionIdle(IoSession session, IdleStatus status) throws Exception {}@Overridepublic void exceptionCaught(IoSession session, Throwable cause) throws Exception {logger.error(cause.getMessage(), cause);session.close(true);}@Overridepublic void messageReceived(IoSession session, Object message) throws Exception {logger.info("Received " + message);MyRequestObject myReqOjb = (MyRequestObject) message;MyResponseObject myResObj = new MyResponseObject(myReqOjb.getName(), myReqOjb.getValue());session.write(myResObj);}@Overridepublic void messageSent(IoSession session, 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 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 the loggingfilter used to record logs and print event messages, and the other is the protocolcodecfilter instance used to encode data, the objectserializationcodecfactory class is used to serialize or deserialize data into Java objects.
3. Create an I/O handler. Here we mainly look at the messagereceived method, which receives the myrequestobject object and sends a myresponseobject object to the client.
4. Finally, bind the ioacceptor class instance to a port for listening.
Check the client 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() {@Overridepublic void sessionCreated(IoSession session) throws Exception {}@Overridepublic void sessionOpened(IoSession session) throws Exception {MyRequestObject myObj = new MyRequestObject("my name", "my value");session.write(myObj);}@Overridepublic void sessionClosed(IoSession session) throws Exception {}@Overridepublic void sessionIdle(IoSession session, IdleStatus status) throws Exception {}@Overridepublic void exceptionCaught(IoSession session, Throwable cause) throws Exception {logger.error(cause.getMessage(), cause);session.close(true);}@Overridepublic void messageReceived(IoSession session, Object message) throws Exception {MyResponseObject myResObj = (MyResponseObject) message;logger.info("Received " + myResObj);session.close(true);}@Overridepublic void messageSent(IoSession session, 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 an I/O service. Here we use the niosocketconnector class to create an ioconnector instance and set the connection timeout to 10 seconds.
2. create an I/O filter chain and set two iofilters on the server. One is the loggingfilter used to record logs and print event messages, and the other is the protocolcodecfilter instance used to encode data, the objectserializationcodecfactory class is also used to serialize or deserialize data into Java objects.
3. Create an I/O handler. Let's take a look at the sessionopened method. In the session creation event, the myrequestobject object is sent, and the myresponseobject object is accepted in the messagereceived method.
4. The ioconnector instance class connects to the remote server.
Next, test the above program. First, run the myserver class, and then run the myclient class to view the event logs and the sent/received objects on the respective terminals.