当前位置:网站首页>Apache MINA框架「建议收藏」
Apache MINA框架「建议收藏」
2022-07-25 20:00:00 【全栈程序员站长】
大家好,又见面了,我是你们的朋友全栈君。
Apache MINA(Multipurpose Infrastructure for Network Applications) 是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络应用程序提供了非常便利的框架。当前发行的 MINA 版本支持基于 Java NIO 技术的 TCP/UDP 应用程序开发、串口通讯程序(只在最新的预览版中提供),MINA 所支持的功能也在进一步的扩展中。目前正在使用 MINA 的软件包括有:Apache Directory Project、AsyncWeb、AMQP(Advanced Message Queuing Protocol)、RED5 Server(Macromedia Flash Media RTMP)、ObjectRADIUS、Openfire 等等。
MINA的几个重要接口:
IoServiece :这个接口在一个线程上负责套接字的建立,拥有自己的 Selector,监听是否有连接被建立。 IoProcessor :这个接口在另一个线程上负责检查是否有数据在通道上读写,也就是说它也拥有自己的 Selector,这是与我们使用 JAVA NIO 编码时的一个不同之处,通常在JAVA NIO 编码中,我们都是使用一个 Selector,也就是不区分 IoService与 IoProcessor 两个功能接口。另外,IoProcessor 负责调用注册在 IoService 上的过滤器,并在过滤器链之后调用 IoHandler。 IoAccepter :相当于网络应用程序中的服务器端,它继承自IoServiece,并进行了扩展。 IoConnector :相当于客户端,它继承自IoServiece,并进行了扩展。 IoSession :当前客户端到服务器端的一个连接实例。 IoHandler :这个接口负责编写业务逻辑,也就是接收、发送数据的地方。这也是实际开发过程中需要用户自己编写的部分代码。 IoFilter :过滤器用于悬接通讯层接口与业务层接口,这个接口定义一组拦截器,这些拦截器可以包括日志输出、黑名单过滤、数据的编码(write 方向)与解码(read 方向)等功能,其中数据的 encode与 decode是最为重要的、也是你在使用 Mina时最主要关注的地方。
MINA的基础架构图:
下面是使用Mina实现TCP的一个小例子:
TCPServer.java
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.service.IoAcceptor;
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.transport.socket.nio.NioSocketAcceptor;
/**
* @description:Mina 实现TcpServer
* @date:(2015-11-22 下午3:46:23)
* @author
* @version v1.0
* @since v1.0
*
* Modified history
*
* Modified date: Modifier user: description:
*
* */
public class TcpServer{
public static void main(String[] args) throws IOException {
IoAcceptor acceptor=new NioSocketAcceptor();
//设置缓冲区大小
acceptor.getSessionConfig().setReadBufferSize(2048);
//设置通道10秒内没有任何操作将处于空闲状态
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
//使用字符串编码
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(
Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue()
,LineDelimiter.WINDOWS.getValue())));
//设置业务处理逻辑
acceptor.setHandler(new MyIOHandler());
acceptor.bind(new InetSocketAddress(9123));
}
}MyIOHandler.java
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
/**
* @description:主要是一些业务逻辑,如发送,接收消息
* @date:(2015-11-24 上午9:37:02)
* @author Administrator
* @version v1.0
* @since v1.0
*
* Modified history
*
* Modified date:
* Modifier user:
* description:
*
* */
public class MyIOHandler extends IoHandlerAdapter{
/**
* 当有异常发生时触发
* */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
super.exceptionCaught(session, cause);
session.close(true);
}
/**
* 有新连接是触发
* */
@Override
public void sessionOpened(IoSession iosession) throws Exception {
System.out.println("session open for " + iosession.getRemoteAddress());
}
/**
* 连接被关闭是触发
* */
@Override
public void sessionClosed(IoSession iosession) throws Exception {
System.out.println("session closed from " + iosession.getRemoteAddress());
}
/**
* 收到来自客户端的消息
*/
@Override
public void messageReceived(IoSession iosession, Object message)
throws Exception {
String str=message.toString();
System.out.println("The message received is [" + str + "]");
if(str.endsWith("quit")){
iosession.close(true);
}
}
}启动服务,在dos窗口中telnet 127.0.0.1 9123
输入:Helllo,MINA.
控制台将输出:
session open for /127.0.0.1:55344 The message received is [hello MINA]
Mina实现TCP客户端:
MyCient.java
import java.net.InetSocketAddress;
import java.nio.charset.Charset;
import org.apache.mina.core.service.IoConnector;
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.transport.socket.nio.NioSocketConnector;
/**
* @description:MINA 实现TCP 客户端
* @date:(2015-11-24 下午10:06:43)
* @author Administrator
* @version v1.0
* @since v1.0
*
* Modified history
*
* Modified date:
* Modifier user:
* description:
*
* */
public class MyCient {
public static void main(String[] args) {
IoConnector connector=new NioSocketConnector();
connector.setConnectTimeoutMillis(30000);
connector.getFilterChain().addLast("codec",
new ProtocolCodecFilter(
new TextLineCodecFactory(Charset.forName("UTF-8"),
LineDelimiter.WINDOWS.getValue(),
LineDelimiter.WINDOWS.getValue())));
connector.setHandler(new ClientHandler("你好!\r\n 大家好!"));
connector.connect(new InetSocketAddress("127.0.0.1", 9123));
}
}ClientHandler.java
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
/**
* @description
* @date:(2015-11-24 下午10:14:04)
* @author Administrator
* @version v1.0
* @since v1.0
*
* Modified history
*
* Modified date:
* Modifier user:
* description:
*
* */
public class ClientHandler extends IoHandlerAdapter{
private String values;
public ClientHandler(String values){
this.values=values;
}
@Override
public void sessionOpened(IoSession session) throws Exception {
session.write(values);
}
}运行TCPServer,java,MyClient.java
server端控制台输出:
session open for /127.0.0.1:56992 The message received is [你好!] The message received is [ 大家好!]
参考文档:
http://www.ibm.com/developerworks/cn/opensource/os-cn-apmina/
http://www.cnblogs.com/xuekyo/archive/2013/03/06/2945826.html
发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/127745.html原文链接:https://javaforall.cn
边栏推荐
- Common misunderstandings caused by a time reporting assistant of Blue Bridge Cup basic questions
- Recommended system topic | Minet: cross domain CTR prediction
- Share 25 useful JS single line codes
- Gbase 8s UDR memory management_ 03_ mi_ realloc
- 919. 完全二叉树插入器
- Prescan quick start to master the special functions of prescan track editing in lecture 18
- 项目中new Promise和async、await中的使用,以及promise.all在项目中的实际应用
- 给容器添加3d效果的副标题
- Distributed link logging minbox logging usage document
- A high efficiency 0-delay 0-copy QT player scheme based on Hisilicon 3559
猜你喜欢

Advantages of network virtualization of various manufacturers

Add a subtitle of 3D effect to the container

Heavy! The new book "deep learning in geometry" was released, which was jointly written by imperial Institute of technology /deepmind and other figures ml Daniel. The 160 page PDF expounds the basic p

IP地址的概念

相机内参矩阵K和fov的相互转换

随机梯度下降法、牛顿法、冲量法、AdaGrad、RMSprop以及Adam优化过程和理解

03 isomorphism of tree 1

When the V100 of mindpole 8 card is trained to 101 epochs, an error of reading data timeout is reported

Is there a "fingerprint" in the structure of AAAI 2022 | Gan? Generating network structure from forged image traceability

wallys//IPQ5018/IPQ6010/PD-60 802.3AT Input Output 10/100/1000M
随机推荐
A good way to generate interface documents efficiently
Add a subtitle of 3D effect to the container
CarSim仿真快速入门(十六)—CarSim传感器仿真之ADAS Sensor Objects (2)
Creative drop-down multi choice JS plug-in download
Can you tell me whether mindspore supports torchvision Model directly uses the pre trained network, such as vgg16
Skiing mobile H5 game source code download
Mindspore1.1.1 source code compilation and installation -- errors in the core compilation stage
Mutual conversion of camera internal parameter matrix K and FOV
Univariate function integration_ Partial integral method
[mindspore] [read graph data] cannot read mindrecord format graph data
基于海思3559 高效率的 0延时 0拷贝 qt播放器方案
Gbase 8s UDR memory management_ 02_ mi_ dalloc
Js分页插件支持表格、列表、文本、图像
How to set tiktok mobile network environment? How can tiktok break the playback volume?
redis源码 -ziplist
From Tong Dai to "Tong Dai" and then to brand, the beauty of sudden profits has changed and remained unchanged
4. Server startup of source code analysis of Nacos configuration center
sentinel简单限流和降级demo问题记录
qml 结合 QSqlTableModel 动态加载数据 MVC「建议收藏」
Typeerror: 'STR' object is not callable error reason