Apache Mina入门实例
一、mina是啥
ApacheMINA是一个网络应用程序框架,用来帮助用户简单地开发高性能和高可扩展性的网络应用程序。它提供了一个通过Java NIO在不同的传输例如TCP/IP和UDP/IP上抽象的事件驱动的异步API。(这是官方文档的翻译)
二、mina可以干啥
现在要用mina写一个服务器和一个客户端通过TCP/IP协议通信的入门实例。
三、mina怎么做到
官方文档上有一幅图画得很好,是关于mina架构的,这里贴上来看一下:

基本上就是这样,一个请求过来,通过IoService,IoService新建一个Session,再通过一大堆的过滤器,最后到了一个处理器里面把业务逻辑处理完后再把结果返回去。
上代码~~~

1、服务器端代码:
MinaServer.java
public class MinaServer {
private static final int Port = 8888;
public void startMinaServer() {
IoAcceptor ioAcceptor = new NioSocketAcceptor();
System.out.println("server start to start!");
//设置过滤器
DefaultIoFilterChainBuilder defaultIoFilterChainBuilder = ioAcceptor.getFilterChain();
defaultIoFilterChainBuilder.addLast("logger", new LoggingFilter());
defaultIoFilterChainBuilder.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
System.out.println("config the filter chain finished!");
//设置处理器
ioAcceptor.setHandler(new FirstServerHandler());
System.out.println("setting the handler finished!");
//配置Session
IoSessionConfig ioSessionConfig = ioAcceptor.getSessionConfig();
ioSessionConfig.setReadBufferSize(2048);
ioSessionConfig.setIdleTime(IdleStatus.BOTH_IDLE, 10);
System.out.println("config the session finished!");
//绑定端口
try {
ioAcceptor.bind(new InetSocketAddress(Port));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("start finish!");
}
public static void main(String[] args) {
MinaServer server = new MinaServer();
server.startMinaServer();
}
}
FirstServerHandler.java
public class FirstServerHandler extends IoHandlerAdapter{
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
super.exceptionCaught(session, cause);
}
private static int message_count = 1;
@Override
public void messageReceived(IoSession session, Object message) {
System.out.println("receive a message.");
String string = message.toString();
if(string.trim().toLowerCase().equals("quit")) {
session.close(true);
return;
}
System.out.println("received message:" + string);
session.write("you are the no. " + message_count + " message!!!");
message_count++;
System.out.println("send back finished!!!");
}
@Override
public void messageSent(IoSession session, Object message){
System.out.println("message have been sent :" + message.toString());
System.out.println();
}
@Override
public void sessionClosed(IoSession session) {
System.out.println("closed Session!");
}
@Override
public void sessionCreated(IoSession session) {
System.out.println("created session!");
}
@Override
public void sessionIdle(IoSession session, IdleStatus status) {
System.out.println("IDLE " + session.getIdleCount(status));
System.out.println();
}
@Override
public void sessionOpened(IoSession session) {
System.out.println("opened session!");
System.out.println();
}
}
2、客户端代码
MinaClient.java
public class MinaClient {
private SocketConnector connector;
private ConnectFuture future;
private IoSession session;
private String server_address = "127.0.0.1";
private int server_port = 8888;
public boolean connect() {
connector = new NioSocketConnector();
DefaultIoFilterChainBuilder defaultIoFilterChainBuilder = connector.getFilterChain();
defaultIoFilterChainBuilder.addLast("logger", new LoggingFilter());
defaultIoFilterChainBuilder.addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory(Charset.forName("UTF-8"))));
connector.setHandler(new FirstClientHandler());
future = connector.connect(new InetSocketAddress(server_address, server_port));
future.awaitUninterruptibly();
session = future.getSession();
session.getConfig().setUseReadOperation(true);
return future.isConnected();
}
public void sendMssageToServer(String message) {
session.write(message);
}
public boolean close() {
CloseFuture closeFuture = session.getCloseFuture();
closeFuture.awaitUninterruptibly(1000);
connector.dispose();
return true;
}
public static void main(String[] args) {
MinaClient client = new MinaClient();
client.connect();
String readLine = "";
Scanner in = new Scanner(System.in);
do {
readLine = in.nextLine();
client.sendMssageToServer(readLine);
}while(!readLine.toLowerCase().equals("quit"));
client.close();
}
}
FirstClientHandler.java
public class FirstClientHandler extends IoHandlerAdapter {
@Override
public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
System.out.println("here got a exception!!!");
super.exceptionCaught(session, cause);
}
@Override
public void messageReceived(IoSession session, Object message) throws Exception {
System.out.println("received a message: " + message.toString());
super.messageReceived(session, message);
}
@Override
public void messageSent(IoSession session, Object message) throws Exception {
System.out.println("sent a message: " + message.toString());
super.messageSent(session, message);
}
@Override
public void sessionCreated(IoSession session) throws Exception {
System.out.println("session created!!!");
super.sessionCreated(session);
}
}
--------------------------------------------我是分割线------------------------------------------------------
3、服务器整合mina
SpringCodeFactory.java
public class SpringCodeFactory implements ProtocolCodecFactory {
private final TextLineEncoder encoder;
private final TextLineDecoder decoder;
/*final static char endchar = 0x1a;*/
final static char endchar = 0x0d;
public SpringCodeFactory() {
this(Charset.forName("UTF-8"));
}
public SpringCodeFactory(Charset charset) {
encoder = new TextLineEncoder(charset, LineDelimiter.UNIX);
decoder = new TextLineDecoder(charset, LineDelimiter.AUTO);
}
@Override
public ProtocolDecoder getDecoder(IoSession session) throws Exception {
return decoder;
}
@Override
public ProtocolEncoder getEncoder(IoSession session) throws Exception {
return encoder;
}
public int getEncoderMaxLineLength() {
return encoder.getMaxLineLength();
}
public void setEncoderMaxLineLength(int maxLineLength) {
encoder.setMaxLineLength(maxLineLength);
}
public int getDecoderMaxLineLength() {
return decoder.getMaxLineLength();
}
public void setDecoderMaxLineLength(int maxLineLength) {
decoder.setMaxLineLength(maxLineLength);
}
}
applicationContext-mina.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean class="org.springframework.beans.factory.config.CustomEditorConfigurer">
<property name="customEditors">
<map>
<entry key="java.net.SocketAddress" value="org.apache.mina.integration.beans.InetSocketAddressEditor">
</entry>
</map>
</property>
</bean> <bean id="executorFilter" class="org.apache.mina.filter.executor.ExecutorFilter" />
<bean id="protocolCodecFilter" class="org.apache.mina.filter.codec.ProtocolCodecFilter">
<constructor-arg>
<bean class="com.misuosi.mina.spring.SpringCodeFactory" />
</constructor-arg>
</bean>
<bean id="loggingFilter" class="org.apache.mina.filter.logging.LoggingFilter" /> <bean id="filterChainBuilder" class="org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder">
<property name="filters">
<map>
<entry key="executor" value-ref="executorFilter"></entry>
<entry key="codec" value-ref="protocolCodecFilter"></entry>
<entry key="logging" value-ref="loggingFilter"></entry>
</map>
</property>
</bean> <bean id="firstServerHandler" class="com.misuosi.mina.server.FirstServerHandler" /> <bean id="ioAcceptor" class="org.apache.mina.transport.socket.nio.NioSocketAcceptor"
init-method="bind" destroy-method="unbind" >
<property name="defaultLocalAddress" value=":8888" />
<property name="handler" ref="firstServerHandler" />
<property name="filterChainBuilder" ref="filterChainBuilder" />
<property name="reuseAddress" value="true" />
</bean> <bean id="sessionConfig" factory-bean="ioAcceptor" factory-method="getSessionConfig" >
<property name="bothIdleTime" value="10"/>
<property name="readBufferSize" value="2048" />
</bean>
</beans>
SpringServer.java
public class SpringServer {
public static void main(String[] args) {
ClassPathXmlApplicationContext ct = new ClassPathXmlApplicationContext("applicationContext-mina.xml");
}
}
四、结果
1、服务器运行结果

2、客户端运行结果

五、参考文档
1、mina官方的用户指南
https://mina.apache.org/mina-project/userguide/user-guide-toc.html
2、Mina入门实例
http://www.cnblogs.com/juepei/p/3939119.html
3、Mina入门教程(二)----Spring4 集成Mina
http://www.w2bc.com/Article/5478
4、mina2.x与spring的集成开发
http://new-restart.iteye.com/blog/1286234
Apache Mina入门实例的更多相关文章
- Apache Mina 入门实例
这个教程是介绍使用Mina搭建基础示例.这个教程内容是以创建一个时间服务器. 以下是这个教程需要准备的东西: MINA 2.0.7 Core JDK 1.5 或更高 SLF4J 1.3.0 或更高 L ...
- Apache Mina入门
Mina第一次听到这个名称的时候,我以为是个MM的名字米娜,后来才知道… Apache MINA(Multipurpose Infrastructure for Network Application ...
- Mina入门实例(一)
mina现在用的很多了,之前也有用到,但是毕竟不熟悉,于是查了一些资料,做了一些总结.看代码是最直观的,比什么长篇大论都要好.不过其中重要的理论,也要理解下. 首先是环境,程序运行需要几个包,这里用m ...
- Mina入门实例
继续上一篇,这篇主要讲通过mina往B端发送消息.并接受消息,mina是一个网络通信框架,封装了javaNIO.简单易用.网上有非常多关于他的介绍,在此不赘述了. 如上篇所介绍,完毕功能,须要五个类: ...
- Apache Shiro入门实例
Shiro是一个强大灵活的开源安全框架,提供身份验证.授权.会话管理.密码体系. 1.先创建一个Maven项目 2.配置pom <project xmlns="http://maven ...
- JAVA通信系列二:mina入门总结
一.学习资料 Mina入门实例(一) http://www.cnblogs.com/juepei/p/3939119.html Mina入门教程(二)----Spring4 集成Mina http:/ ...
- Mina入门教程(二)----Spring4 集成Mina
在spring和mina集成的时候,要十分注意一个问题:版本. 这是一个非常严重的问题,mina官网的demo没错,网上很多网友总结的代码也是对的,但是很多人将mina集成到spring中的时候,总是 ...
- Apache MiNa 实现多人聊天室
Apache MiNa 实现多人聊天室 开发环境: System:Windows JavaSDK:1.6 IDE:eclipse.MyEclipse 6.6 开发依赖库: Jdk1.4+.mina-c ...
- Apache Mina(一)
原文链接:http://www.cnblogs.com/xuekyo/archive/2013/03/06/2945826.html Apache Mina是一个能够帮助用户开发高性能和高伸缩性网络应 ...
随机推荐
- 这是一款可以查阅Github上的热门趋势的APP
随时查阅当前Github上的热门趋势.使用Material Design设计风格,和流行的MVP+Retrofit+RxJava框架.数据抓取自https://github.com/trending ...
- 初学jQuery之jQuery选择器
今天我们就谈论一下jquery选择器,它们大致分成了四种选择器!!!! 1.基本选择器(标签,ID,类,并集,交集,全局) 1.0(模板) <body> <div id=" ...
- Java Web(五) JSP详解(四大作用域九大内置对象等)
前面讲解了Servlet,了解了Servlet的继承结构,生命周期等,并且在其中的ServletConfig和ServletContext对象有了一些比较详细的了解,但是我们会发现在Servlet中编 ...
- c++ 调用dl里的导出类
来源:http://blog.csdn.net/yysdsyl/article/details/2626033 动态dll的类导出:CPPDll2->test.h #pragma once // ...
- NSInternalInconsistencyException attempt to delete row 2 from section 4 which only contains 0 rows before the update 问题原因
insertRowsAtIndexPaths 和 deleteRowsAtIndexPaths 同 numberOfRowsInSection 的关系 如果不处理好这个关系,大概所有的问题都是这样的: ...
- web前端页面性能
前段性能的意义 对于访问一个网站,最花费时间的并不是后端应用程序处理以及数据库等消耗的时间,而是前端花费的时间(包括请求.网络传输.页面加载.渲染等).根据web优化的黄金法则:80%的最终用户响应时 ...
- 每天一个linux命令(29)--Linux chmod命令
chmod 命令用于改变Linux 系统文件或目录的访问权限.用它控制文件或目录的访问权限.该命令有两种用法.一种是包含字母和操作符表达式的文字设定法:另一种是包含数字的数字设定法. Linux系统中 ...
- PHP链接Redis
命令行下运行 redis-server.exe redis.windows.conf 此时,redis服务已经开启,然后我们可以再新开一个命令行,作为控制台 redis-cli.exe -h 127. ...
- perl 获取系统时间
最近需要将字符串转换成时间,找了下资料,实战如下,发现时timelocal费了些时间 strftime也可在 c / c++ / awk / php 中使用,用法基本一致. 这个也不错 $time = ...
- Selenium 使用Eclipse+TestNG创建一个Project中遇到的问题
继续之前的学习,对于一个没有太多计算机基础的人,刚学习selenium,最大的问题就是不知道该如何入手,最简单的办法就是录制脚本之后导入. 但是导入的时候也会出现一些问题,就是该导入到哪里?如何导入? ...