最近使用Mina开发一个在线聊天的项目,因此也特意学习了Apache的这个Mina框架。
首先,Mina是个什么东西?看下官方网站(http://mina.apache.org/)对它的解释:
Apache的Mina(Multipurpose Infrastructure Networked Applications)是一个网络应用框架,可以帮助用户开发高性能和高扩展性的网络应用程序;它提供了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发。
Apache Mina也称为:
- NIO框架
- 客户端/服务端框架(典型的C/S架构)
- 网络套接字(networking socket)类库
- 事件驱动的异步API(注意:在JDK7中也新增了异步API)
总之:我们简单理解它是一个封装底层IO操作,提供高级操作API的通讯框架!
在Mina的官网、以及网上都有比较丰富的文档了,这里我就稍微简单说一下Mina的结构和示例代码。
因为Mina2.X改进了Mina的代码结构和包结构,降低了使用的复杂性和增强了健壮性,所以使得API发生了比较大的改变,有许多地方已经和Mina1.x不兼容了。
我这里要实现的是在线聊天功能,所以其中使用的数据并不单一,所以这里采用了JOSN的数据格式,我这里是采用UTF-8的编码,代码中用到的JSON的2个处理包:json-lib-2.3-jdk15.jar、ezmorph-1.0.6.jar。
使用的Mina版本为2.0.4
具体的开发过程,比如导包和建立项目什么的我就不说了,这里直接上代码。
(1)服务端代码TcpServer
我这里使用的是Mina自带TextLineCodecFactory
- package com.lrcx.ky.server;
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import java.util.concurrent.Executors;
- import org.apache.mina.core.service.IoServiceStatistics;
- import org.apache.mina.core.session.IdleStatus;
- import org.apache.mina.filter.codec.ProtocolCodecFilter;
- import org.apache.mina.filter.codec.textline.LineDelimiter;
- import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
- import org.apache.mina.filter.executor.ExecutorFilter;
- import org.apache.mina.transport.socket.SocketAcceptor;
- import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
- public class TcpServer {
- private int port = 8292;
- private int idleTime = 1800;
- private int bufferSize = 1024;
- private SocketAcceptor acceptor;
- public void start() {
- acceptor = new NioSocketAcceptor(Runtime.getRuntime().availableProcessors() + 1);
- TextLineCodecFactory lineCodec = new TextLineCodecFactory(Charset
- .forName("UTF-8"), LineDelimiter.WINDOWS.getValue(),
- LineDelimiter.WINDOWS.getValue());
- lineCodec.setDecoderMaxLineLength(2*1024*1024);
- lineCodec.setEncoderMaxLineLength(2*1024*1024);
- acceptor.getFilterChain().addLast("codec", new ProtocolCodecFilter(lineCodec));
- acceptor.getFilterChain().addLast("exceutor", new ExecutorFilter(Executors.newCachedThreadPool()));
- acceptor.setHandler(new TcpHandler());
- acceptor.setReuseAddress(true);
- acceptor.setBacklog(10240);
- acceptor.getSessionConfig().setReuseAddress(true);
- acceptor.getSessionConfig().setReadBufferSize(bufferSize);
- acceptor.getSessionConfig().setReceiveBufferSize(bufferSize);
- acceptor.getSessionConfig().setTcpNoDelay(true);
- acceptor.getSessionConfig().setSoLinger(-1);
- // 单位秒
- acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, idleTime);
- try {
- acceptor.bind(new InetSocketAddress(port));
- } catch (IOException e) {
- e.printStackTrace();
- System.exit(0);
- }
- }
- public void stop() {
- acceptor.dispose();
- }
- }
代码中的这两行:
lineCodec.setDecoderMaxLineLength(2*1024*1024);
lineCodec.setEncoderMaxLineLength(2*1024*1024);是用来设置每次传输文本的长度的。
(2)服务端处理器代码TcpHandler
- package com.lrcx.ky.server;
- import net.sf.json.JSONObject;
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IdleStatus;
- import org.apache.mina.core.session.IoSession;
- public class TcpHandler extends IoHandlerAdapter {
- @Override
- public void messageReceived(IoSession session, Object message)
- throws Exception {
- JSONObject request = JSONObject.fromObject(message.toString());
- // 根据传来的数据进行处理
- System.out.println(request);
- }
- @Override
- public void exceptionCaught(IoSession session, Throwable cause)
- throws Exception {
- }
- @Override
- public void sessionClosed(IoSession session) throws Exception {
- }
- @Override
- public void sessionIdle(IoSession session, IdleStatus status)
- throws Exception {
- }
- }
(3)客户端代码TcpClient
- package com.lrcx.ky.site.client;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import java.util.concurrent.Executors;
- import net.sf.json.JSONObject;
- import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
- import org.apache.mina.core.future.CloseFuture;
- import org.apache.mina.core.future.ConnectFuture;
- import org.apache.mina.core.session.IoSession;
- import org.apache.mina.filter.codec.ProtocolCodecFilter;
- import org.apache.mina.filter.codec.textline.LineDelimiter;
- import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
- import org.apache.mina.filter.executor.ExecutorFilter;
- import org.apache.mina.transport.socket.SocketConnector;
- import org.apache.mina.transport.socket.nio.NioSocketConnector;
- public class TcpClient {
- private SocketConnector connector;
- private ConnectFuture future;
- private IoSession session;
- public boolean connect() {
- try {
- // 创建一个socket连接
- connector = new NioSocketConnector();
- // 设置链接超时时间
- connector.setConnectTimeoutMillis(3000);
- // 获取过滤器链
- DefaultIoFilterChainBuilder filterChain = connector.getFilterChain();
- // 添加编码过滤器 处理乱码、编码问题
- TextLineCodecFactory lineCodec = new TextLineCodecFactory(Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue());
- lineCodec.setDecoderMaxLineLength(2*1024*1024);
- lineCodec.setEncoderMaxLineLength(2*1024*1024);
- filterChain.addLast("codec", new ProtocolCodecFilter(lineCodec));
- filterChain.addLast("exceutor", new ExecutorFilter(Executors.newCachedThreadPool()));
- // 消息核心处理器
- connector.setHandler(new TcpHandler());
- // 连接服务器,知道端口、地址
- future = connector.connect(new InetSocketAddress("127.0.0.1", 8292));
- // 等待连接创建完成
- future.awaitUninterruptibly();
- // 获取当前session
- session = future.getSession();
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- public void write(JSONObject request) throws Exception {
- session.write(request.toString());
- }
- public boolean close() {
- try {
- CloseFuture future = session.getCloseFuture();
- future.awaitUninterruptibly(1000);
- connector.dispose();
- return true;
- } catch (Exception e) {
- e.printStackTrace();
- return false;
- }
- }
- }
(4)客户端处理器代码TcpHandler
- package com.lrcx.ky.site.client;
- import net.sf.json.JSONObject;
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IoSession;
- public class TcpHandler extends IoHandlerAdapter {
- public void messageReceived(IoSession session, Object message) throws Exception {
- JSONObject request = JSONObject.fromObject(message.toString());
- // 根据传来的数据进行处理
- System.out.println(request);
- }
- public void exceptionCaught(IoSession session, Throwable cause)
- throws Exception {
- }
- public void sessionClosed(IoSession session) throws Exception {
- }
- }
以上是客户端和服务端通信的基础代码,具体的业务逻辑大家可以在这个基础上随意发挥。