当前位置:网站首页>Apache Mina framework "suggestions collection"
Apache Mina framework "suggestions collection"
2022-07-25 20:05:00 【Full stack programmer webmaster】
Hello everyone , I meet you again , I'm your friend, Quan Jun .
Apache MINA(Multipurpose Infrastructure for Network Applications) yes Apache Organize a new project , It provides a very convenient framework for the development of high-performance and high availability network applications . The current issue of MINA Version support is based on Java NIO technology TCP/UDP Application development 、 Serial communication program ( Only available in the latest preview ),MINA The supported functions are also in further expansion . Currently in use MINA The software includes :Apache Directory Project、AsyncWeb、AMQP(Advanced Message Queuing Protocol)、RED5 Server(Macromedia Flash Media RTMP)、ObjectRADIUS、Openfire wait .
MINA Several important interfaces :
IoServiece : This interface is responsible for socket establishment on a thread , Own your own Selector, Monitor whether a connection is established . IoProcessor : This interface is responsible for checking whether data is read and written on the channel on another thread , That is to say, it has its own Selector, This is used with us JAVA NIO A difference in coding , Usually in JAVA NIO In the encoding , We all use one Selector, That is to say, there is no distinction IoService And IoProcessor Two functional interfaces . in addition ,IoProcessor Responsible for calling registration in IoService Filter on , And after the filter chain is called IoHandler. IoAccepter : It is equivalent to the server side in network applications , It is inherited from IoServiece, And expanded . IoConnector : Equivalent to the client , It is inherited from IoServiece, And expanded . IoSession : A connection instance from the current client to the server . IoHandler : This interface is responsible for writing business logic , That is to receive 、 Where data is sent . This is also part of the code that users need to write themselves in the actual development process . IoFilter : The filter is used to suspend the communication layer interface and the service layer interface , This interface defines a set of interceptors , These interceptors can include log output 、 Blacklist filtering 、 Coding of data (write Direction ) And decoding (read Direction ) And so on , Where the data encode And decode Is the most important 、 You're also using Mina The main concern when .
MINA The infrastructure diagram of :
Here's how to use Mina Realization TCP A small example of :
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 Realization TcpServer
* @date:(2015-11-22 Afternoon 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();
// Set buffer size
acceptor.getSessionConfig().setReadBufferSize(2048);
// Set up channels 10 No operation in seconds will be idle
acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
// Use string encoding
acceptor.getFilterChain().addLast("codec",
new ProtocolCodecFilter(new TextLineCodecFactory(
Charset.forName("UTF-8"), LineDelimiter.WINDOWS.getValue()
,LineDelimiter.WINDOWS.getValue())));
// Set business processing logic
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: Mainly some business logic , If sent , receive messages
* @date:(2015-11-24 In the morning 9:37:02)
* @author Administrator
* @version v1.0
* @since v1.0
*
* Modified history
*
* Modified date:
* Modifier user:
* description:
*
* */
public class MyIOHandler extends IoHandlerAdapter{
/**
* Trigger when an exception occurs
* */
@Override
public void exceptionCaught(IoSession session, Throwable cause)
throws Exception {
super.exceptionCaught(session, cause);
session.close(true);
}
/**
* A new connection is triggered
* */
@Override
public void sessionOpened(IoSession iosession) throws Exception {
System.out.println("session open for " + iosession.getRemoteAddress());
}
/**
* When the connection is closed
* */
@Override
public void sessionClosed(IoSession iosession) throws Exception {
System.out.println("session closed from " + iosession.getRemoteAddress());
}
/**
* Received a message from the client
*/
@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);
}
}
}Start the service , stay dos Window telnet 127.0.0.1 9123
Input :Helllo,MINA.
The console will output :
session open for /127.0.0.1:55344 The message received is [hello MINA]
Mina Realization TCP client :
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 Realization TCP client
* @date:(2015-11-24 Afternoon 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(" Hello !\r\n Hello everyone !"));
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 Afternoon 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);
}
}function TCPServer,java,MyClient.java
server End console output :
session open for /127.0.0.1:56992 The message received is [ Hello !] The message received is [ Hello everyone !]
Reference documents :
http://www.ibm.com/developerworks/cn/opensource/os-cn-apmina/
http://www.cnblogs.com/xuekyo/archive/2013/03/06/2945826.html
Publisher : Full stack programmer stack length , Reprint please indicate the source :https://javaforall.cn/127745.html Link to the original text :https://javaforall.cn
边栏推荐
- tiktok如何破零播放?
- Security Basics 4 - regular expressions
- Notes - record a cannotfinddatasourceexception: dynamic datasource can not find primary datasource problem solving
- [artifact] screenshot + mapping tool snipaste
- what is qml in qt
- Distributed link logging minbox logging usage document
- "Share" devaxpress asp Net v22.1 latest version system environment configuration requirements
- Sentinel simple current limiting and degradation demo problem record
- C语言学习日记3——realloc函数
- 各厂商网络虚拟化的优势
猜你喜欢

C language learning diary 3 - realloc function

Do you still have certificates to participate in the open source community?

Concept of IP address

Sentinel simple current limiting and degradation demo problem record

Share 25 useful JS single line codes

Timing analysis and constraints based on xlinx (1) -- what is timing analysis? What are temporal constraints? What is temporal convergence?

Skiing mobile H5 game source code download

sentinel简单限流和降级demo问题记录

Advantages of network virtualization of various manufacturers

When the V100 of mindpole 8 card is trained to 101 epochs, an error of reading data timeout is reported
随机推荐
VMware 虚拟机下载、安装和使用教程
从瞳代到“瞳代”再到品牌,暴利的美瞳的变与未变
【高等数学】【3】微分中值定理与导数的应用
redis源码 -ziplist
Dataloader reports an error "default_collate: batch must contain tensors, numpy arrays, numbers, dicts" when pytorch trains the model
PyTorch 模型 onnx 文件的导出和调用
C语言学习日记3——realloc函数
When the V100 of mindpole 8 card is trained to 101 epochs, an error of reading data timeout is reported
A high efficiency 0-delay 0-copy QT player scheme based on Hisilicon 3559
When AI encounters life and health, Huawei cloud builds three bridges for them
Export and call of onnx file of pytorch model
PMP每日一练 | 考试不迷路-7.25
笔记——记录一个CannotFindDataSourceException: dynamic-datasource can not find primary datasource问题解决
Split very long line of words into separate lines of max length
9. < tag dynamic programming and subsequence, subarray> lt.718. Longest repeated subarray + lt.1143. Longest common subsequence
The use of new promise, async and await in the project, and the practical application of promise.all in the project
PMP practice once a day | don't get lost in the exam -7.25
Cloud native guide: what is cloud native infrastructure
tiktok如何破零播放?
Deeplobv1 and V2