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是一个能够帮助用户开发高性能和高伸缩性网络应 ...
随机推荐
- Spring装配Bean---使用xml配置
声明Bean Spring配置文件的根元素是<beans>. 在<beans>元素内,你可以放所有的Spring配置信息,包括<bean>元素的声明. 除了Bean ...
- API模板
#include <windows.h> #include <windowsx.h> #define DIVISIONS 5 LRESULT CALLBACK WndProc ...
- CEOI 2014 wall (最短路)
描述:给定一个网格图,每个区间可能会有城市,求在边上建墙使无法从外边到达所有城市切所有城市必须联通 n,m<=400 首先对于30%的数据,n,m<=10我们可以考虑用数位dp来解决这个问 ...
- BZOJ 3412: [Usaco2009 Dec]Music Notes乐谱(离线处理)
这道题貌似怎么写都可以吧= =,我先读入询问然后从小到大处理就行了= = PS:水水题真的好!无!聊!但是好!欢!乐! CODE: #include<cstdio>#include< ...
- 在 Windows 上测试 Redis Cluster的集群填坑笔记
redis 集群实现的原理请参考http://www.tuicool.com/articles/VvIZje 集群环境至少需要3个节点.推荐使用6个节点配置,即3个主节点,3个从节点. 新 ...
- 漂亮的代码2:遍历文件夹目录,使用promise
看到一个问题: 找到文件夹下所有文件: 自己写了一个: function walk(dir, ext, callback) { ext = ext.charAt(0) === "." ...
- Java编程风格学习(三)
在上一篇的java编程风格学习(二)中我们学习了一些在Java编码过程中的格式规范,遵循这些规范毋庸置疑是我们的书写高质量代码的前提与基础.今天我们更进一步,一起来学习Java编程的命名规范,向着编写 ...
- 【CNMP系列】CentOS7.0下安装PHP5.6.30服务
上一节我们讲过了如何在CentOS7.0下安装MySql服务,如果没有看到欢迎页面的朋友,可以加我的个人微信详聊:litao514148204 附上一节地址:http://www.cnblogs.co ...
- EFcore与动态模型(二)
上篇文章中介绍了如何使用ef进行动态类型的管理,比如我们定义了ShopDbContext并且注册了动态模型信息,下面的代码实现了动态信息的增加: Type modelType = IRuntimeMo ...
- 【Scala】Scala之Object
一.前言 前面学习了Scala的Methods,接着学习Scala中的Object 二.Object Object在Scala有两种含义,在Java中,其代表一个类的实例,而在Scala中,其还是一个 ...