Mina传递对象
利用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传递对象的更多相关文章
- Message和handler传递对象
Bundle可以传递对象,message又可以传递Bundle于是就可以利用buddle作为中间载体传递对象了 Message msg = Message.obtain(); Bundle b = ...
- Android 全局获取 Context 与使用 Intent 传递对象
=====================全局获取 Context======================== Android 开发中很多地方需要用到 Context,比如弹出 Toast.启动活 ...
- Android--Intent传递对象
Intent 传递对象通常有两种实现方式,Serializable 和 Parcelable: 一.Serializable:序列化,表示将一个对象转换成可存储或可传输的状态,序列化后的对象可以在网络 ...
- 实现在GET请求下调用WCF服务时传递对象(复合类型)参数
WCF实现RESETFUL架构很容易,说白了,就是使WCF能够响应HTTP请求并返回所需的资源,如果有人不知道如何实现WCF支持HTTP请求的,可参见我之前的文章<实现jquery.ajax及原 ...
- Android中如何使用Intent在Activity之间传递对象[使用Serializable或者Parcelable]
http://blog.csdn.net/cjjky/article/details/6441104 在Android中的不同Activity之间传递对象,我们可以考虑采用Bundle.putSeri ...
- Intent传递对象的两种方法(Serializable,Parcelable) (转)
今天讲一下Android中Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是Bundle.putParcela ...
- Intent传递对象的两种方法
Android为intent提供了两种传递对象参数类型的方法 分别需要使实体类实现Serializable接口.Parcelable接口 首先我们要知道,传递对象,需要先将对象序列化 一.那么为什么要 ...
- Android中Intent传递对象的两种方法(Serializable,Parcelable)
今天要给大家讲一下Android中 Intent中如何传递对象,就我目前所知道的有两种方法,一种是Bundle.putSerializable(Key,Object);另一种是 Bundle.putP ...
- 利用Bundle在activity之间传递对象
(2010-12-04 09:45:54) 转载▼ 标签: it 分类: android开发 转自:http://chen592969029.javaeye.com/blog/772656 假如需要在 ...
随机推荐
- 【Redis】Redis分布式集群几点说道
Redis数据量日益增大,使用的公司越来越多,不仅用于做缓存,同时趋向于存储这一块,这样必促使集群的发展,各个公司也在收集适合自己的集群方案,目前行业用的比较多的是下面几种集群架构,大部分都是采用分片 ...
- css 中的度量单位
px 相对长度单位.像素(Pixel). 像素是相对于显示器屏幕分辨率而言的.譬如,WONDOWS的用户所使用的分辨率一般是96像素/英寸.而MAC的用户所使用的分辨率一般是72像素/英寸. em 相 ...
- delphi提示“Undeclared_identifier”的缺少引用单元列表
_Stream ADODB_TLB akTop, akLeft, akRight, akBottom Controls Application (the variable not a type) Fo ...
- OSG addEventHandler W键 L键 F键
// add the state manipulator viewer->addEventHandler( new osgGA::StateSetManipulator(viewer-&g ...
- mac OS X 安装svn
因为从10.5版本开始适用Mac OS,SVN一直都是默认安装的软件. 后来发现一个简单的办法. 如果你有安装XCode,只需要在code > Preferences > download ...
- 查看Linus中自带的jdk ,设置JAVA_HOME
在配置hadoop是,进行格式化hadoop的时候,出现找不到jdk 我用Red hat是32位的,没有现成的32位的,敲java , 发现本机有java ,就找了一下其位置 找到了jdk-1.6.0 ...
- SVN服务器搭建和使用(一)(转载)
转载地址:http://www.cnblogs.com/xiaobaihome/archive/2012/03/20/2407610.html Subversion是优秀的版本控制工具,其具体的的优点 ...
- Java Hour 32 Weather ( 5 ) struts2 – Action class
有句名言,叫做10000小时成为某一个领域的专家.姑且不辩论这句话是否正确,让我们到达10000小时的时候再回头来看吧. Hour 32 Struts2 Action 1 将action 映射到 ac ...
- hdu 1806 rmq
找到一个区间内出现最多的数的次数 10 3 //10个数字三次询问 -1 -1 1 1 1 1 3 10 10 10 2 3 1 10 5 10 0 143 #include<cstdio> ...
- hdu 1059 多重背包
题意:价值分别为1,2,3,4,5,6的物品个数分别为a[1],a[2],a[3],a[4],a[5],a[6],问能不能分成两堆价值相等的. 解法:转化成多重背包 #include<stdio ...