Apache MINA实战之 对象传输

fmms 10年前

本文链接:http://blog.csdn.net/kongxx/article/details/7520599

利用Apache MINA来传递对象,这对了MINA来说非常容易,并且这也是Java网络编程中很常用的应用。其实对于MINA传递对象来说,如果看过前一篇文章的话,只要在其中做少许改动就可以实现对象传递,但这里考虑到例子的完整性,还是给出了全部代码示例。

首先看两个用来传递的Java对象MyRequestObject和MyResponseObject,很简单只是实现了Serializable接口罢了。

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();   }  }
看看Server端的代码
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 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);      MyRequestObject myReqOjb = (MyRequestObject) message;      MyResponseObject myResObj = new MyResponseObject(myReqOjb.getName(), myReqOjb.getValue());      session.write(myResObj);     }       @Override     public 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. 首先创建I/O Service,这里使用的是NioSocketAcceptor类来创建了一个IoAcceptor实例。

2. 创建I/O Filter Chain,这里使用了两个个IoFilter,一个是LoggingFilter用来记录日志和打印事件消息,另一个是 ProtocolCodecFilter实例用来编码数据,这里使用了ObjectSerializationCodecFactory类来序列化或反序列化数据成java对象。

3. 创建I/O Handler,这里主要看一下messageReceived方法,其总接收了MyRequestObject对象,然后又发送了一个MyResponseObject对象给Client端。

4. 最后就是让IoAcceptor类实例绑定端口实现监听。

 

看看Client端的代码

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 Exception {     }       @Override     public void sessionOpened(IoSession session) throws Exception {      MyRequestObject myObj = new MyRequestObject("my name", "my value");      session.write(myObj);     }       @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 {      MyResponseObject myResObj = (MyResponseObject) message;      logger.info("Received " + myResObj);      session.close(true);     }       @Override     public 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. 首先创建I/O Service,这里使用的是NioSocketConnector类来创建了一个IoConnector实例,并设置连接超时为10秒。

2. 创建I/O Filter Chain,和服务器端同样设置了两个IoFilter,一个是LoggingFilter用来记录日志和打印事件消息,另一个是 ProtocolCodecFilter实例用来编码数据,这里也使用了ObjectSerializationCodecFactory类来序列化或反序列化数据成java对象。

3. 创建I/O Handler,主要看一下sessionOpened方法,其中在会话建立事件中发送了MyRequestObject对象,然后在messageReceived方法中又接受了MyResponseObject对象。

4. 最后就是IoConnector实例类连接远端的Server。

 

下面测试一下上面的程序,首先运行MyServer类,然后运行MyClient类,就可以分别在各自的终端上看到事件日志以及发送/接收的对象了。