码迷,mamicode.com
首页 > 其他好文 > 详细

Mina传递对象

时间:2014-09-02 19:38:05      阅读:188      评论:0      收藏:0      [点我收藏+]

标签:style   blog   color   os   io   java   ar   数据   div   

利用Apache MINA来传递对象,这对了MINA来说非常容易,并且这也是Java网络编程中很常用的应用。 

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

MyRequestObject.java

package demo5.vo;

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();
    }
}

MyResponseObject.java

package demo5.vo;

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端的代码

MyServer.java

package demo5.server;

import java.io.IOException;
import java.net.InetSocketAddress;

import org.apache.mina.core.service.IoAcceptor;
import org.apache.mina.core.session.IdleStatus;
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) {
        int bindPort = 10000;
        
        IoAcceptor acceptor = new NioSocketAcceptor();
        
        //调用IoSessionConfig设置读取数据的缓冲区大小、读写通道均在10秒内无任何操作就进入空闲状态
        acceptor.getSessionConfig().setReadBufferSize(2048);
        acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
        
        acceptor.getFilterChain().addLast("logger", new LoggingFilter());
        acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new ObjectSerializationCodecFactory()));

        acceptor.setHandler(new MyServerHandler());
        
        try {
            acceptor.bind(new InetSocketAddress(bindPort));
        } catch (IOException ex) {
            logger.error(ex.getMessage(), ex);
        }
    }
}

MyServerHandler.java

package demo5.server;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import demo5.vo.MyRequestObject;
import demo5.vo.MyResponseObject;

public class MyServerHandler extends IoHandlerAdapter{
    private static final Logger logger = LoggerFactory.getLogger(MyServerHandler.class);
    
    @Override
    public void sessionCreated(IoSession session) throws Exception {
        System.out.println("IP:"+session.getRemoteAddress().toString());
    }
    
    @Override
    public void sessionOpened(IoSession session) throws Exception {
    }

    @Override
    public void sessionClosed(IoSession session) throws Exception {
        System.out.println("IP:"+session.getRemoteAddress().toString()+"断开连接");
    }

    @Override
    public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
        System.out.println( "IDLE " + session.getIdleCount( status ));
    }

    @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);
    }

}

Client端代码:

MyClient.java

package demo5.client;

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.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) {
        int bindPort = 10000;
        String ip="localhost";
        
        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 MyClientHandler());

        IoSession session = null;
        try {
            ConnectFuture future = connector.connect(new InetSocketAddress(ip, bindPort));
            future.awaitUninterruptibly();
            session = future.getSession();
        } catch (RuntimeIoException e) {
            logger.error(e.getMessage(), e);
        }

        session.getCloseFuture().awaitUninterruptibly();
        connector.dispose();
    }
}

MyClientHandler.java

package demo5.client;

import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IdleStatus;
import org.apache.mina.core.session.IoSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import demo5.vo.MyRequestObject;
import demo5.vo.MyResponseObject;

public class MyClientHandler extends IoHandlerAdapter{
    private static final Logger logger = LoggerFactory.getLogger(MyClientHandler.class);
    
    @Override
    public void sessionCreated(IoSession session) throws Exception {
    }

    @Override
    public void sessionOpened(IoSession session) throws Exception {
        MyRequestObject myObj = new MyRequestObject("我的name", "我的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);
    }

}

 

Mina传递对象

标签:style   blog   color   os   io   java   ar   数据   div   

原文地址:http://www.cnblogs.com/gisblogs/p/3951984.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!