认识:
Apache
MINA 2 是一个开发高性能和高可伸缩性网络应用程序的网络应用框架。它提供了一个抽象的事件驱动的异步 API,可以使用
TCP/IP、UDP/IP、串口和虚拟机内部的管道等传输方式。Apache MINA 2 可以作为开发网络应用程序的一个良好基础。
学习MINA的原因:
由
于项目中使用到了socket,并且使用的是传统阻塞式socket编程,项目二期的时候发现生产环境过一段时间就会内存溢出,性能也没有一个好的保证,
用检测工具发现线程很多阻塞了。以前公司都没有做过socket程序占大部分的这种项目,对于我们而言也只能网上找资料学习了。前一段时间对IM即时通讯
感兴趣就玩了下openfire,听说底层也是mina,当时也不知道MINA是个什么东东,没注意。后来随着我对我们项目框架的思考,发现我们开发人员
自己来写socket底层,一来socket这块比较生疏,不容易写好,弄不好哪里没关闭导致什么问题出现都说不定。二来技术人员很容易钻到技术实现这一
块来,而不是更多的去关注实现业务。这样非常不好,我在想是否有一种开源框架,帮我们封装好了socket底层,我们只需要用它就可以了呢,找了下,果然
有,不过普遍反应mina比较好,而且是非阻塞的(关于阻塞和非阻塞有什么区别,网上有很多资料),所以就选择学习mina
了,之所以学习它是因为想在后期优化项目中现有socket程序。
我自己实现的例子介绍(我使用自定义编解码):
ProtocolCodecFilter 用
来在字节流和消息对象之间互相转换。当该过滤器接收到字节流的时候,需要首先判断消息的边界,然后把表示一条消息的字节提取出来,通过一定的逻辑转换成消
息对象,再把消息对象往后传递,交给 I/O
处理器来执行业务逻辑。这个过程称为“解码”。与“解码”对应的是“编码”过程。在“编码”的时候,过滤器接收到的是消息对象,通过与“解码”相反的逻
辑,把消息对象转换成字节,并反向传递,交给 I/O 服务来执行 I/O 操作。
在“编码”和“解码”中的一个重要问题是如何在字节流中判断消息的边界。通常来说,有三种办法解决这个问题:
- 使用固定长度的消息。这种方式实现起来比较简单,只需要每次读取特定数量的字节即可。
- 使用固定长度的消息头来指明消息主体的长度。比如每个消息开始的 4 个字节的值表示了后面紧跟的消息主体的长度。只需要首先读取该长度,再读取指定数量的字节即可。
- 使用分隔符。消息之间通过特定模式的分隔符来分隔。每次只要遇到该模式的字节,就表示到了一个消息的末尾。
具体到示例应用来说,客户端和服务器之间的通信协议比较复杂,有不同种类的消息。每种消息的格式都不相同,同类消息的内容也不尽相同。因此,使用固定长度的消息头来指明消息主体的长度就成了最好的选择。
mina编解码流程:request->MyDecoder->MyHandler->MyEncode->response
---------------------自定义编解码代码实现----------------------------
解码:MyProtocalDecoder.java
编码:MyProtocalEncoder.java
- package com.ccic.mina.myprotocal;
-
- import java.nio.charset.Charset;
-
- import org.apache.mina.core.buffer.IoBuffer;
- import org.apache.mina.core.session.IoSession;
- import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
- import org.apache.mina.filter.codec.ProtocolEncoderOutput;
-
- public class MyProtocalEncoder extends ProtocolEncoderAdapter {
- private final Charset charset;
-
- public MyProtocalEncoder(Charset charset) {
- this.charset = charset;
- }
-
-
- public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
- String value = (String) message;
- IoBuffer buf = IoBuffer.allocate(value.getBytes().length);
- buf.setAutoExpand(true);
- if (value != null)
- buf.put(value.trim().getBytes());
- buf.flip();
- out.write(buf);
- }
-
-
- }
编解码工厂类:MyProtocalCodecFactory.java
- package com.ccic.mina.myprotocal;
-
- import java.nio.charset.Charset;
-
- import org.apache.mina.core.session.IoSession;
- import org.apache.mina.filter.codec.ProtocolCodecFactory;
- import org.apache.mina.filter.codec.ProtocolDecoder;
- import org.apache.mina.filter.codec.ProtocolEncoder;
-
- public class MyProtocalCodecFactory implements ProtocolCodecFactory {
- private final MyProtocalEncoder encoder;
- private final MyProtocalDecoder decoder;
-
- public MyProtocalCodecFactory(Charset charset) {
- encoder = new MyProtocalEncoder(charset);
- decoder = new MyProtocalDecoder(charset);
- }
-
- public ProtocolEncoder getEncoder(IoSession session) {
- return encoder;
- }
-
- public ProtocolDecoder getDecoder(IoSession session) {
- return decoder;
- }
-
- }
Handler类:MyHandler.java
- package com.ccic.mina.myprotocal;
-
- import org.apache.mina.core.service.IoHandlerAdapter;
- import org.apache.mina.core.session.IdleStatus;
- import org.apache.mina.core.session.IoSession;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
-
- class MyHandler extends IoHandlerAdapter {
- private final static Logger LOGGER = LoggerFactory.getLogger(MyHandler.class);
-
- @Override
- public void sessionOpened(IoSession session) throws Exception {
- LOGGER.info(" session is Opened..." + session.getId());
- }
-
- @Override
- public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
-
- session.close(true);
- }
-
- @Override
- public void messageReceived(IoSession session, Object message) throws Exception {
- String pack = (String) message;
-
-
-
-
- session.write(pack);
- }
-
- @Override
- public void sessionIdle(IoSession session, IdleStatus status) throws Exception {
- LOGGER.info("IDLE " + session.getIdleCount(status));
- }
- }
客户端: MyProtocalClient.java
- package com.ccic.mina.myprotocal;
-
- import java.io.BufferedReader;
- import java.io.DataOutputStream;
- import java.io.InputStreamReader;
- import java.net.Socket;
-
- public class MyProtocalClient {
-
-
- public static void main(String[] args) {
- try {
- Socket socket = new Socket("127.0.0.1", 8080);
- DataOutputStream out = new DataOutputStream(socket.getOutputStream());
- InputStreamReader inputStreamReader = new InputStreamReader(socket.getInputStream());
- BufferedReader in = new BufferedReader(inputStreamReader);
- for (int i = 0; i < 200; i++) {
- long startTime = System.currentTimeMillis();
- String str = "2BC0A039329D8FF6F4CB8BAA71A45FED8E119BEB76F0F1B1AA99F73B867C1685AF0F903F10F65505A4D618E30C0A1A9046FF3301A368AD36A7ADC78761E6C4C758D2611F3F3E3C448E63CE1B2CA88ACF7C54F44AC3621D927C16E5C4876FFDF51392FF7BFE8392420B6125504F53AB5C5CB1C350EA67BE577B6DB689F63C47B5F5593C55B607667240A57DF820109A13194C42AA1F3205771AB9E3C359555BC973FF59DD752E19CB472B61D8FA910A0C820A2677A2032723A00E87079F0A79BB9ACA930EBF7F25BC31AA7E1DA70810FC2ABA508269185FC6306082E966D82464CBF07B77502962EE378629C74B26BD3B536CDAA049D3841B36B7B7A4E9EC95CDE330ABFCD594DF4FAE3DEEB99DBC8DDA054F4D6B0F0EAEE82A21771A92635CAD9FFE021A2A408BC7C40060CCA98C77FEB8A7F5BC8AD5A64CF58BC0D5C9ED56D1E2450A2A674E53093BC015E2CEFC1D9B6B8BC79B85868C47586632DDEA08ED9EEE31A4DC9D777C28AD65892E1C5E1260AFF9299E162FE3276CF1A0FAD89878FF89ACEFF48C2B0FCD07E272C834F0C07C1838A39F019D1184232688F40AC0AE2F302B8F20A12F7D7511042E7B68E0C07D3B94CC61609097B9B7062B9DEE91E73DCDD268CBD247DB2348311A4EC1A7CAA554287C464F751960624236313976D16B5C735F1083FD18CC1FB56614A3B9B7F32249A38FD1A6EF235369E2311D6C964F2D459C75EA732BD1F3095BB2DA5821655974E1A53E5EBDA47652000D563F52A48CA00F395EDAEC58EEBE8D46C57886F8C5811E6C8F5A979DE911249F07370FB8BEF8BB35E0E64608EC43581DFBFEABE6C11337FD05DCBDC9242EBFD42D82DD59D72682D3C94945FEB03051153863CD3556E6B87BABCF1A5B01698D459FD01CFB7C28C650E0A8FE575C8E380601D55E517DF5852F07A49CF982635FA1E4689AF1D9B94F02D8F00B4AED356401FF6FFC1FC73C99D3025C08096FEF6659F32EA4D53279FAC697D56339F1A5F689E806F0F900A09A8F4CDB64B5DACEF7D6DC06460217234794DB61CC5AD6E8534B4BA5FB3B38B8D195E3B71AEBA4983606E00ECDC644CFFC5696140C78767139B3806C68F4906810030BC23DFE91C1C8CD11F758CCB3E4BCFD254B5D3959EC7F7764CE76DB74E117E7F844ADA94F99B02AC961A87C3084358D6B64540898788BDAA8455F374B607C7ACAB489BE099AB7C7AD78EFF8C1405A90DDAF23EB5D454167178620458227922B8A8E9E1D8D980089FBFC8143BA8FFD96E49A18C32BAEFB088956A75192805D44C5C2BFB345D6FA54A74C8B8B6BD566F24DB3BAB58F71BDB03807A566DEFCAC57889F2CE4803B39D64AF61291D3C56A5C0B4F3C3E287CAD8540505E23A24EA2D4815A742ED7F9173F8C157735B8D7FA20727E013E5BEECEF3DAC27960E7BA025D5335952AC1C0CBB94523835574FCB1E5B5E1782FC1EFA9B0471F3D443F6104C13698929D2FCE5B2220BF9DCD125CA8F8918826A48F960CEE66E01AB5F066630E1793277838E0F997D8C8A01C086387BB2718C7CA1A1C3BB46223CE0B367DD86DCA768D50F41BB40188709103D2C854044DE2653002EEB78965D8141B5A6900B17A94A6846CA2595436E45DA841F6DC3165187DAF6499DB5B15233A7205D9CB70D8776F109C6B744A0DA3ADC4EABEFA6C83C28BC2BC4C3389CF792F1AC9B544290D1A5C0CCBD69E89183A08A5B2496398358A6005FD404EF89678BE00FA0034C192D5B089A92083F93C5E8A8E36367A9DA75B463A6566806FACB47E71C4276F45D294CE54E7292DBD092E8D6D74C474D49D94BA5594090EDD12AC06DE72DDEC2AB56AD94C";
- String temp_ = "";
- int SUB_COUNT = 1000;
-
- out.writeInt(2608 + 8);
-
- for (int c = 0; c < str.getBytes().length / SUB_COUNT; c++) {
- if (temp_ == "" && temp_.length() == 0) {
- temp_ = str.substring(c * SUB_COUNT, SUB_COUNT);
-
- out.write(temp_.getBytes());
- } else {
-
- out.write(str.substring(c * SUB_COUNT, (c + 1) * SUB_COUNT).getBytes());
-
-
- int raim_ = str.substring((c + 1) * SUB_COUNT, str.getBytes().length).length();
- if (raim_ < SUB_COUNT && raim_ != 0) {
- out.write(str.substring((c + 1) * SUB_COUNT, str.getBytes().length).getBytes());
- }
- }
- }
-
- out.flush();
- System.out.println(i + " sended");
-
- char temp[] = new char[2700];
- String backLine = "";
- in.read(temp);
- backLine = String.valueOf(temp).trim();
- System.out.println("backLine==" + backLine);
- long endTime = System.currentTimeMillis();
- System.out.println("程序运行时间(毫秒): " + (endTime - startTime) + "ms");
- }
- Thread.sleep(1000);
- out.close();
- in.close();
- socket.close();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
服务端类:MyProtocalServer.java
- package com.ccic.mina.myprotocal;
-
- import java.io.IOException;
- import java.net.InetSocketAddress;
- import java.nio.charset.Charset;
- import java.util.concurrent.Executors;
-
- import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder;
- 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.executor.ExecutorFilter;
- import org.apache.mina.filter.logging.LogLevel;
- import org.apache.mina.filter.logging.LoggingFilter;
- import org.apache.mina.transport.socket.nio.NioSocketAcceptor;
-
-
-
-
-
-
-
- public class MyProtocalServer {
- private static final int PORT = 8080;
-
-
-
- public static void main(String[] args) throws IOException {
-
- IoAcceptor acceptor = new NioSocketAcceptor();
-
-
-
- LoggingFilter loggingFilter = new LoggingFilter();
- loggingFilter.setSessionCreatedLogLevel(LogLevel.NONE);
- loggingFilter.setSessionOpenedLogLevel(LogLevel.NONE);
- loggingFilter.setSessionClosedLogLevel(LogLevel.NONE);
- loggingFilter.setMessageReceivedLogLevel(LogLevel.NONE);
- loggingFilter.setMessageSentLogLevel(LogLevel.NONE);
- loggingFilter.setSessionIdleLogLevel(LogLevel.INFO);
- loggingFilter.setExceptionCaughtLogLevel(LogLevel.INFO);
-
- acceptor.getFilterChain().addLast("logger", loggingFilter);
-
- acceptor.getFilterChain().addLast("codec",
- new ProtocolCodecFilter(new MyProtocalCodecFactory(Charset.forName("UTF-8"))));
-
- acceptor.getSessionConfig().setReadBufferSize(3000);
-
- acceptor.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, 10);
-
-
-
- DefaultIoFilterChainBuilder filterChainBuilder = acceptor.getFilterChain();
- filterChainBuilder.addLast("threadPool", new ExecutorFilter(Executors.newCachedThreadPool()));
-
- acceptor.setHandler(new MyHandler());
- acceptor.bind(new InetSocketAddress(PORT));
- System.out.println("Start server is listenig at port " + PORT);
- }
- }
运行:
启动服务端server: MyProtocalServer->Main方法
客户端:MyProtocalClient->Main方法
阅读(13395) | 评论(0) | 转发(0) |