Apache Mina Server 是一个网络通信应用框架,对socket进行了封装。

http://www.cnblogs.com/moonandstar08/p/5475766.html

http://blog.csdn.net/u010739551/article/details/47361365

http://www.cnblogs.com/yanghuiping/p/4108063.html  (mina 自定义编解码)

Client端:

public class MinaClient {

    public static void main(String[] args) throws Exception{
//1.
NioSocketConnector connector = new NioSocketConnector();
//2.
connector.setHandler(new MyClientHandler());
//3.所有收发的消息都会经过拦截器,经拦截器进行消息的处理
connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));
//4.
ConnectFuture future = connector.connect(new InetSocketAddress("127.0.0.1", 9898));
future.awaitUninterruptibly();
IoSession session = future.getSession();
BufferedReader inputReader = new BufferedReader(new InputStreamReader(System.in));
String inputContent;
while (!(inputContent = inputReader.readLine()).equals("bye")) {
session.write(inputContent);
}
} }

将网络和消息处理的代码分开

public class MyClientHandler extends IoHandlerAdapter {

    @Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
System.out.println("exceptionCaught");
} @Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String s = (String) message;
System.out.println("messageReceived: " + s);
} @Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("messageSent");
} @Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("sessionClosed");
} @Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("sessionCreated");
} @Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("sessionIdle");
} @Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("sessionOpened");
} }

Server端:

public class MinaServer {

    public static void main(String[] args) {
try {
//1.
NioSocketAcceptor acceptor = new NioSocketAcceptor();
//2.网络管理和消息处理的分割开来; MyServerHandler()专门处理消息分发和会话管理
acceptor.setHandler(new MyServerHandler());
//3.拦截器,责任链设计模式。所有收发的消息全部要经过拦截器过滤之后,消息才可以收发;
//网络上传输是字节,拦截器做对象的转换工作;
//ProtocolCodecFilter 二进制数据和对象进行转化;MyTextLineFactory()内置的,对传输数据进行加解码
acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(new MyTextLineFactory()));
//每隔5秒,检查客户端是否处于空闲狂态,检测客户端是否掉线
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 5);
//4.服务器端口启动起来,监听9898
acceptor.bind(new InetSocketAddress(9898));
} catch (IOException e) {
e.printStackTrace();
}
} }
public class MyServerHandler extends IoHandlerAdapter {

    @Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
System.out.println("exceptionCaught");
} @Override
public void messageReceived(IoSession session, Object message)
throws Exception {
String s = (String) message;
System.out.println("messageReceived: " + s);
session.write("server reply: " + s);
} @Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("messageSent");
} @Override
public void sessionClosed(IoSession session) throws Exception {
System.out.println("sessionClosed");
} @Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("sessionCreated");
}

//客户端进入空闲状态,检测 客户端 是否掉线
@Override
public void sessionIdle(IoSession session, IdleStatus status)
throws Exception {
System.out.println("sessionIdle");
} @Override
public void sessionOpened(IoSession session) throws Exception {
System.out.println("sessionOpened");
} }
public class MyTextLineFactory implements ProtocolCodecFactory {

    private MyTextLineDecoder mDecoder;

    private MyTextLineCumulativeDecoder mCumulativeDecoder;

    private MyTextLineEncoder mEncoder;

    public MyTextLineFactory () {
mDecoder = new MyTextLineDecoder();
mEncoder = new MyTextLineEncoder();
mCumulativeDecoder = new MyTextLineCumulativeDecoder();
} @Override
public ProtocolDecoder getDecoder(IoSession arg0) throws Exception {
return mCumulativeDecoder;
} @Override
public ProtocolEncoder getEncoder(IoSession arg0) throws Exception {
return mEncoder;
} }
public class MyTextLineCumulativeDecoder extends CumulativeProtocolDecoder {

    @Override
protected boolean doDecode(IoSession session, IoBuffer in,
ProtocolDecoderOutput out) throws Exception {
int startPosition = in.position();
while (in.hasRemaining()) {
byte b = in.get();
if (b == '\n') {
int currentPositoin = in.position();
int limit = in.limit();
in.position(startPosition);
in.limit(currentPositoin);
IoBuffer buf = in.slice();
byte [] dest = new byte[buf.limit()];
buf.get(dest);
String str = new String(dest);
out.write(str);
in.position(currentPositoin);
in.limit(limit);
return true;
}
}
in.position(startPosition);
return false;
} }
public class MyTextLineEncoder implements ProtocolEncoder {

    @Override
public void dispose(IoSession arg0) throws Exception { } @Override
public void encode(IoSession session, Object message, ProtocolEncoderOutput out)
throws Exception {
String s =null;
if (message instanceof String) {
s = (String) message;
}
if (s != null) {
CharsetEncoder charsetEndoer = (CharsetEncoder)session.getAttribute("encoder");
if (charsetEndoer == null) {
charsetEndoer = Charset.defaultCharset().newEncoder();
session.setAttribute("encoder", charsetEndoer);
}
IoBuffer ioBuffer = IoBuffer.allocate(s.length());
ioBuffer.setAutoExpand(true);
ioBuffer.putString(s, charsetEndoer);
ioBuffer.flip();
out.write(ioBuffer);
}
} }
public class MyTextLineDecoder implements ProtocolDecoder {

    @Override
public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
throws Exception {
int startPosition = in.position();
while (in.hasRemaining()) {
byte b = in.get();
if (b == '\n') {
int currentPositoin = in.position();
int limit = in.limit();
in.position(startPosition);
in.limit(currentPositoin);
IoBuffer buf = in.slice();
byte [] dest = new byte[buf.limit()];
buf.get(dest);
String str = new String(dest);
out.write(str);
in.position(currentPositoin);
in.limit(limit);
}
}
} @Override
public void dispose(IoSession arg0) throws Exception { } @Override
public void finishDecode(IoSession arg0, ProtocolDecoderOutput arg1)
throws Exception { } }

android开发学习——Mina框架的更多相关文章

  1. Android开发学习——Volley框架

    转载至: http://blog.csdn.net/guolin_blog/article/details/17482095 一些概念性的东西 大家进入上边链接理解,我贴一下 具体的实现代码: pub ...

  2. Android开发学习路线图

    Android开发学习方法: Android是一个比较庞大的体系,从底层的Linux内核到上层的应用层,各部分的内容跨度也比较大.因此,一个好的学习方法对我们学习Android开发很重要. 在此建议, ...

  3. Android开发学习之路--Android系统架构初探

    环境搭建好了,最简单的app也运行过了,那么app到底是怎么运行在手机上的,手机又到底怎么能运行这些应用,一堆的电子元器件最后可以运行这么美妙的界面,在此还是需要好好研究研究.这里从芯片及硬件模块-& ...

  4. Android开发学习路线的七个阶段和步骤

    Android开发学习路线的七个阶段和步骤           Android学习参考路线     第一阶段:Java面向对象编程 1.Java基本数据类型与表达式,分支循环. 2.String和St ...

  5. Android开发学习之路-RecyclerView滑动删除和拖动排序

    Android开发学习之路-RecyclerView使用初探 Android开发学习之路-RecyclerView的Item自定义动画及DefaultItemAnimator源码分析 Android开 ...

  6. android开发学习笔记000

    使用书籍:<疯狂android讲义>——李刚著,2011年7月出版 虽然现在已2014,可我挑来跳去,还是以这本书开始我的android之旅吧. “疯狂源自梦想,技术成就辉煌.” 让我这个 ...

  7. Android开发学习总结(一)——搭建最新版本的Android开发环境

    Android开发学习总结(一)——搭建最新版本的Android开发环境(转) 最近由于工作中要负责开发一款Android的App,之前都是做JavaWeb的开发,Android开发虽然有所了解,但是 ...

  8. Android开发学习之LauncherActivity开发启动的列表

    Android开发学习之LauncherActivity开发启动的列表 创建项目:OtherActivity 项目运行结果:   建立主Activity:OtherActivity.java [jav ...

  9. 最实用的Android开发学习路线分享

    Android开发学习路线分享.Android发展主导移动互联发展进程,在热门行业来说,Android开发堪称火爆,但是,虽然Android有着自身种种优势,但对开发者的专业性要求也是极高,这种要求随 ...

随机推荐

  1. python的序列化和反序列化以及json

    python 的序列化和反序列化用于内存之间的共享,包括服务器和客户端的共享,两个Python程序之间的共享,以及以字符串的形式存储到硬盘中. pyhton 的pickle 可以对Python的各种数 ...

  2. MVC的验证(模型注解和非侵入式脚本的结合使用) .Net中初探Redis .net通过代码发送邮件 Log4net (Log for .net) 使用GDI技术创建ASP.NET验证码 Razor模板引擎 (RazorEngine) .Net程序员应该掌握的正则表达式

    MVC的验证(模型注解和非侵入式脚本的结合使用)   @HtmlHrlper方式创建的标签,会自动生成一些属性,其中一些属性就是关于验证 如图示例: 模型注解 通过模型注解后,MVC的验证,包括前台客 ...

  3. [iOS]经常使用正則表達式

    经常使用正則表達式大全!(比如:匹配中文.匹配html) 匹配中文字符的正則表達式: [u4e00-u9fa5]    评注:匹配中文还真是个头疼的事,有了这个表达式就好办了 匹配双字节字符(包含汉字 ...

  4. Hibernate 之 一级缓存

    本篇文章主要是总结Hibernate中关于缓存的相关内容. 先来看看什么是缓存,我们这里所说的缓存主要是指应用程序与物流数据源之间(例如硬盘),用于存放临时数据的内存区域,这样做的目的是为了减少应用程 ...

  5. Koa2学习(八)使用session

    Koa2学习(八)使用session koa2框架不提供session的处理方法,这里我们需要借助一个第三方中间件koa-session来处理session. 先安装插件: $ npm i koa-s ...

  6. os 2大功能

    支撑功能 中断管理 时钟管理 原语操作  primitive 资源管理功能 进程管理 存储器管理 设备管理

  7. haproxy tcp 反向代理

    配置如下: global log 127.0.0.1 local3 warning nbproc 1 maxconn 65535 daemon defaults log global option d ...

  8. 并不对劲的manacher算法

    有些时候,后缀自动机并不能解决某些问题,或者解决很麻烦.这时就有各种神奇的字符串算法了. manacher算法用来O(|S|)地求出字符串S的最长的回文子串的长度.这是怎么做到的呢? 并不对劲的暴力选 ...

  9. lua 与 c 的相互调用

    Lua是一个嵌入式的语言,意味着Lua不仅可以是一个独立运行的程序包也可以是一个用来嵌入其他应用的程序库. Lua可以作为程序库用来扩展应用的功能,也就是Lua可以作为扩展性语言的原因所在.同时,Lu ...

  10. jsp中page指令用法详解

    转自:https://www.jb51.net/article/73428.htm 一.JSP 指令 JSP 指令(directive)影响由 JSP 页面生成的 servlet 的整体结构.下面的模 ...