利用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传递对象的更多相关文章

  1. Message和handler传递对象

    Bundle可以传递对象,message又可以传递Bundle于是就可以利用buddle作为中间载体传递对象了 Message msg = Message.obtain();  Bundle b =  ...

  2. Android 全局获取 Context 与使用 Intent 传递对象

    =====================全局获取 Context======================== Android 开发中很多地方需要用到 Context,比如弹出 Toast.启动活 ...

  3. Android--Intent传递对象

    Intent 传递对象通常有两种实现方式,Serializable 和 Parcelable: 一.Serializable:序列化,表示将一个对象转换成可存储或可传输的状态,序列化后的对象可以在网络 ...

  4. 实现在GET请求下调用WCF服务时传递对象(复合类型)参数

    WCF实现RESETFUL架构很容易,说白了,就是使WCF能够响应HTTP请求并返回所需的资源,如果有人不知道如何实现WCF支持HTTP请求的,可参见我之前的文章<实现jquery.ajax及原 ...

  5. Android中如何使用Intent在Activity之间传递对象[使用Serializable或者Parcelable]

    http://blog.csdn.net/cjjky/article/details/6441104 在Android中的不同Activity之间传递对象,我们可以考虑采用Bundle.putSeri ...

  6. Intent传递对象的两种方法(Serializable,Parcelable) (转)

    今天讲一下Android中Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcela ...

  7. Intent传递对象的两种方法

    Android为intent提供了两种传递对象参数类型的方法 分别需要使实体类实现Serializable接口.Parcelable接口 首先我们要知道,传递对象,需要先将对象序列化 一.那么为什么要 ...

  8. Android中Intent传递对象的两种方法(Serializable,Parcelable)

    今天要给大家讲一下Android中 Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是 Bundle.putP ...

  9. 利用Bundle在activity之间传递对象

    (2010-12-04 09:45:54) 转载▼ 标签: it 分类: android开发 转自:http://chen592969029.javaeye.com/blog/772656 假如需要在 ...

随机推荐

  1. Linux统计文件个数

    查看某个文件夹下的文件个数用ls列目录,用grep过虑,再用wc统计即可 用ls -l列出后, 每一行对应一个文件或目录, 如果第一个字母为’-'则为普通文件, 若为’d'则为子目录 + +grep过 ...

  2. ios抓包官方文档

    OS X Programs OS X supports a wide range of packet trace programs, as described in the following sec ...

  3. 【SpringMVC】SpringMVC系列11之Restful的CRUD

      11.Restful的CRUD 11.1.需求 11.2.POST转化为PUT.DELETE的fileter 11.3.查询所有 11.4.添加 11.5.删除     优雅的 REST 风格的资 ...

  4. SQL表值函数和标量值函数的区别

    SQL表值函数和标量值函数的区别 写sql存储过程经常需要调用一些函数来使处理过程更加合理,也可以使函数复用性更强,不过在写sql函数的时候可能会发现,有些函数是在表值函数下写的有些是在标量值下写的, ...

  5. SQL— CONCAT(字符串连接函数)

    有的时候,我们有需要将由不同栏位获得的资料串连在一起.每一种资料库都有提供方法来达到这个目的: MySQL: CONCAT() Oracle: CONCAT(), || SQL Server: + C ...

  6. sybaseIQ索引类型和使用注意事项

    1. FP(Fast Projection)此索引为默认的索引形式,在创建表时系统自动设置此索引. 特点:用于SELECT.LIKE '%sys%'.SUM(A+B).JOIN操作等语句. 此类型索引 ...

  7. 一些LUA函数(转载)

    转自http://hi.baidu.com/chevallet/item/9a3a6410c20d929198ce3363 一些LUA函数 1.assert (v [, message]) 功能:相当 ...

  8. js判空

    2014年9月3日 11:36:10 转载的: http://blog.sina.com.cn/s/blog_755168af0100vsik.html typeof用法 typeof的运算数未定义, ...

  9. 桐桐的贸易--WA

    问题 A: 桐桐的贸易 时间限制: 1 Sec  内存限制: 64 MB提交: 15  解决: 2[提交][状态][讨论版] 题目描述 桐桐家在Allianceance城,好友ROBIN家在Horde ...

  10. UVALive 7040 Color (容斥原理+逆元+组合数+费马小定理+快速幂)

    题目:传送门. 题意:t组数据,每组给定n,m,k.有n个格子,m种颜色,要求把每个格子涂上颜色且正好适用k种颜色且相邻的格子颜色不同,求一共有多少种方案,结果对1e9+7取余. 题解: 首先可以将m ...