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是一个能够帮助用户开发高性能和高伸缩性网络应 ...
随机推荐
- 前端开发面试题总结之——JAVASCRIPT(一)
___________________________________________________________________________________ 相关知识点 数据类型.运算.对象 ...
- Java静态代理和动态代理总结
静态代理 第一种实现(基于接口): 1>接口 public interface Hello { void say(String msg);} 2>目标类,至少实现一个接口 public c ...
- H5中背景音乐无法自动播放问题
苹果禁止了Autoplay和JS "onload" 加载播放,使在html文件里使用了preload和autoplay属性,在移动版 Safari 上,此属性会被忽视,并且不会加载 ...
- windows 地址空间分配
当系统创建一个进程同时为其创建它地址空间时,此地址空间中大部分都是闲置的.为了使用这部分地址空间,我们必须调用VirtualAlloc来分配其中的区域.分配区域的操作被称为预定. 当应用程序预定地址空 ...
- 以setTimeout来聊聊Event Loop
平时的工作中,也许你会经常用到setTimeout这个方法,可是你真的了解setTimeout吗?本文想通过总结setTimeout的用法,顺便来探索javascript里面的事件执行机制. setT ...
- 软件测试作业1 — 令我印象最深的BUG
回顾从大一到大三的学习生活,我在学习过程中遇到过许多BUG,刚开始和罗凯老师学习C++时从来没有接触过编程,那时候导致程序不能运行的原因多是语法错误和拼写错误,到了大一下学期,错误多出现在循环与条件跳 ...
- 每天一个Linux命令(16)--which命令
把昨天的,留给昨天:今日,你将重新开始. 好的,在第一个阶段我们学习了 文件目录的操作命令: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 ls cd pwd mkdir ...
- 如何用一张图片代替 'input:file' 上传本地文件??
今天去面试,碰到了一道题,也许是因为紧张或者喝水喝多了,一时竟然没有转过弯来,回来之后一细想原来这么简单,哭笑不得,特此记录一下! 原题是这样的: 如何用一张图片代替 'input:file' 上传 ...
- Git commit message和工作流规范
目的 统一团队Git commit日志标准,便于后续代码review,版本发布以及日志自动化生成等等. 统一团队的Git工作流,包括分支使用.tag规范.issue等 Git commit日志参考案例 ...
- 指针与数据结构算法_链表(C语言)
一.变量: 声明一个变量系统是没有给这个变量分配内存空间的: 例: int j;//编译的时候是没有分配内存空间的 ;//计算机在编译的时候就会给这个i分配4个字节的内存空间 二.malloc动态分配 ...