- 浏览: 981297 次
文章分类
- 全部博客 (428)
- Hadoop (2)
- HBase (1)
- ELK (1)
- ActiveMQ (13)
- Kafka (5)
- Redis (14)
- Dubbo (1)
- Memcached (5)
- Netty (56)
- Mina (34)
- NIO (51)
- JUC (53)
- Spring (13)
- Mybatis (17)
- MySQL (21)
- JDBC (12)
- C3P0 (5)
- Tomcat (13)
- SLF4J-log4j (9)
- P6Spy (4)
- Quartz (12)
- Zabbix (7)
- JAVA (9)
- Linux (15)
- HTML (9)
- Lucene (0)
- JS (2)
- WebService (1)
- Maven (4)
- Oracle&MSSQL (14)
- iText (11)
- Development Tools (8)
- UTILS (4)
- LIFE (8)
最新评论
-
Donald_Draper:
Donald_Draper 写道刘落落cici 写道能给我发一 ...
DatagramChannelImpl 解析三(多播) -
Donald_Draper:
刘落落cici 写道能给我发一份这个类的源码吗Datagram ...
DatagramChannelImpl 解析三(多播) -
lyfyouyun:
请问楼主,执行消息发送的时候,报错:Transport sch ...
ActiveMQ连接工厂、连接详解 -
ezlhq:
关于 PollArrayWrapper 状态含义猜测:参考 S ...
WindowsSelectorImpl解析一(FdMap,PollArrayWrapper) -
flyfeifei66:
打算使用xmemcache作为memcache的客户端,由于x ...
Memcached分布式客户端(Xmemcached)
Apache Mina(一):http://www.cnblogs.com/xuekyo/archive/2013/03/06/2945826.html
引言:
Mina是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP
协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务、虚拟机管道通信服务等),
Mina 可以帮助我们快速开发高性能、高扩展性的网络通信应用,Mina 提供了事件驱动、异
步(Mina 的异步IO 默认使用的是JAVA NIO 作为底层支持)操作的编程模型。Mina的相关组件IoService,IoProcessor,IoFilter,IoHanler,IoBuffer的含义,可以搜索相关文章,这里不再赘述。
今天我们来看一个简单的TCP通信实例,实例所用MINA版本为2.0.16:
server:
server handler:
client:
client handler:
本实例中的handler的继承IoHandlerAdapter,在实际开发中,我们不需要实现所有方法,我们只需要实现关注的方法即可比如sessionOpened,
messageReceived,exceptionCaught,sessionClosed。
启动server,client控制台输出:
server:
[INFO ] 2017-05-21 10:46:31 mina.tcp.main.SimpleServer =========SimpleServer is start============
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter CREATED
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========Session Created...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter OPENED
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========Session Opened...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:Hello Server...
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:I'm Client...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========messageSent...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========messageSent...
[INFO ] 2017-05-21 10:46:53 org.apache.mina.filter.logging.LoggingFilter IDLE
[DEBUG] 2017-05-21 10:46:53 mina.tcp.handler.SimpleServerHandler (0x00000001: nio socket, server, /192.168.126.135:60519 => /192.168.126.135:9122)=========Session Idle...
client:
[INFO ] 2017-05-21 10:46:43 mina.tcp.main.SimpleClient =========SimpleClient is start============
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter CREATED
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========Session Created...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter OPENED
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========messageSent...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:Hello Client...
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:I'm Server...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:server test...Hello Client...
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:I'm Server...
从上面的日志可以看出,LoggingFilter的输出在Handler日志前面,证明了,IoService发送的数据要经过IoFilter层,再由IoHandler处理。由于我们用的是TextLineCodecFactory(按行发送与接收数据),从日志输出来,client将多行数据一次发送,而server将发送过来的多行数据分行读取;client发送的为
Hello Server...\r\nI'm Client...\r\nclient test...
而server收到的为
1.Hello Server...
2.I'm Client...
这两行后面的client test...没有收到,证明TextLineCodecFactory是按行发送与接收数据,不到一行数据,不解析数据。
由于server接受了两次client发送过来的数据,并回复
Hello Client...\r\nI'm Server...\r\nserver test...
从client的输出来看,
第一次接收事件:
Hello Client...
I'm Server...
第二次接收事件:
server test...Hello Client...
I'm Server...
从上面可以看出,第一次没有解析完的数据留在缓冲区中,与下一次接收的数据合并处理。
整个过程:
client发生一次发送事件,server一次接收事件,多次调用handler处理行数据,并产生了多次发送事件,client相应的产生多次接收事件,并将上一次没有解析完的数据,与下一次接收的数据合并处理。
过滤器:
再来测试一下IoFilter,编写测试IoFilter
注意在filter*和session*及exceptionCaught方法调用时,要NextFilter相应方法,这一点和web的Filter#doFilter相似。
修改上一个实例中的Server端:
启动SimpleServerWithTestFilter,server,及上例中的client,
SimpleServerWithTestFilter控制台输出:
[INFO ] 2017-05-21 00:51:54 mina.tcp.main.SimpleServerWithTestFilter =========SimpleServer is start============
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$init...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$onPreAdd...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$onPostAdd...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter CREATED
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$sessionCreated...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========Session Created...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter OPENED
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$sessionOpened...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========Session Opened...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 00:52:00 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageReceived...
[INFO ] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:Hello Server...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$filterWrite...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageReceived...
[INFO ] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:I'm Client...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$filterWrite...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageSent...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========messageSent...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageSent...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========messageSent...
从日志输出来看,init,onPreAdd,onPostAdd事件在会话创建时已经发生,这些方法主要用于初始化过滤器,添加过滤器到IoService
的过滤链时触发。会话事件顺序CREATED-》OPENED-》RECEIVED。从上面的日志输出可以看出整个过程的处理顺序为,
SimpleServerWithTestFilter-》LoggingFilter-》TestFilter-》ProtocolCodecFilter-》SimpleServerHandler,
过滤器的顺序默认为添加的顺序。在每次过滤器捕捉到接收数据事件,都将调用filterWrite方法。
引言:
Mina是一个网络通信应用框架,也就是说,它主要是对基于TCP/IP、UDP/IP
协议栈的通信框架(当然,也可以提供JAVA 对象的序列化服务、虚拟机管道通信服务等),
Mina 可以帮助我们快速开发高性能、高扩展性的网络通信应用,Mina 提供了事件驱动、异
步(Mina 的异步IO 默认使用的是JAVA NIO 作为底层支持)操作的编程模型。Mina的相关组件IoService,IoProcessor,IoFilter,IoHanler,IoBuffer的含义,可以搜索相关文章,这里不再赘述。
今天我们来看一个简单的TCP通信实例,实例所用MINA版本为2.0.16:
server:
package mina.tcp.main; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; 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.codec.textline.LineDelimiter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.SocketSessionConfig; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import mina.tcp.handler.SimpleServerHandler; /** * simple Server-TextLineCodecFactory * @author donald * 2017年5月19日 * 上午8:59:37 */ public class SimpleServer { private static final Logger log = LoggerFactory.getLogger(SimpleServer.class); private static final String ip = "192.168.126.135"; private static final int port = 9122; private static final int readBufferSize = 2048; private static final int idleTime = 10; private static final Charset charset = Charset.forName("UTF-8"); public static void main(String[] args) throws IOException { IoAcceptor acceptor=new NioSocketAcceptor(); //配置socket会话 SocketSessionConfig socketSessionConfig = (SocketSessionConfig) acceptor.getSessionConfig(); socketSessionConfig.setReadBufferSize(readBufferSize); socketSessionConfig.setIdleTime(IdleStatus.BOTH_IDLE,idleTime); //配置过滤器 DefaultIoFilterChainBuilder defaultIoFilterChainBuilder = acceptor.getFilterChain(); LoggingFilter loggingFilter = new LoggingFilter(); defaultIoFilterChainBuilder.addLast("loggingFilter", loggingFilter); TextLineCodecFactory textLineCodecFactory = new TextLineCodecFactory(charset,LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue()); ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(textLineCodecFactory); defaultIoFilterChainBuilder.addLast("protocolCodecFilter",protocolCodecFilter); //配置NioSocketAcceptor处理器 SimpleServerHandler simpleServerHandler = new SimpleServerHandler(); acceptor.setHandler(simpleServerHandler); InetSocketAddress inetSocketAddress = new InetSocketAddress(ip,port); acceptor.bind(inetSocketAddress); log.info("=========SimpleServer is start============"); } }
server handler:
package mina.tcp.handler; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import org.apache.mina.core.buffer.IoBuffer; 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; /** * simple server handler * @author donald * 2017年5月19日 * 下午1:13:45 */ public class SimpleServerHandler extends IoHandlerAdapter { private final static Logger log = LoggerFactory.getLogger(SimpleServerHandler.class); private static final CharsetEncoder charsetEncoder= Charset.forName("UTF-8").newEncoder(); private static final CharsetDecoder charsetDecoder= Charset.forName("UTF-8").newDecoder(); public void messageReceived(IoSession session, Object message) throws Exception { String msg = (String) message; log.info("=========The message received from Client is:" + msg); //收到客户端发送的关闭会话命令 /*if(msg.equals("quit")){ session.closeNow(); }*/ IoBuffer buffer = IoBuffer.allocate(1024); buffer.putString("Hello Client...\r\nI'm Server...\r\nserver test...", charsetEncoder); buffer.flip(); session.write(buffer); } @Override public void sessionClosed(IoSession session) throws Exception { log.debug("=========Session Closed..."); } @Override public void sessionCreated(IoSession session) throws Exception { log.debug("=========Session Created..."); } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { log.debug(session + "=========Session Idle..."); } @Override public void sessionOpened(IoSession session) throws Exception { log.debug("=========Session Opened..."); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { log.error(cause.getMessage()); cause.printStackTrace(); session.closeNow(); } @Override public void messageSent(IoSession session, Object message) throws Exception { log.debug("=========messageSent..."); } }
client:
package mina.tcp.main; import java.net.InetSocketAddress; import java.nio.charset.Charset; import org.apache.mina.core.filterchain.DefaultIoFilterChainBuilder; 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.filter.logging.LoggingFilter; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import mina.tcp.handler.SimpleClientHandler; /** * Simple Client - TextLineCodecFactory * @author donald * 2017年5月19日 * 下午1:04:10 */ public class SimpleClient { private static final Logger log = LoggerFactory.getLogger(SimpleClient.class); private static final String ip = "192.168.126.135"; private static final int port = 9122; private static final int connectTimeoutMillis = 30000; private static final Charset charset = Charset.forName("UTF-8"); public static void main(String[] args) { IoConnector connector=new NioSocketConnector(); connector.setConnectTimeoutMillis(connectTimeoutMillis); //配置过滤器 DefaultIoFilterChainBuilder defaultIoFilterChainBuilder = connector.getFilterChain(); LoggingFilter loggingFilter = new LoggingFilter(); defaultIoFilterChainBuilder.addLast("loggingFilter", loggingFilter); TextLineCodecFactory textLineCodecFactory = new TextLineCodecFactory(charset,LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue()); ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(textLineCodecFactory); defaultIoFilterChainBuilder.addLast("protocolCodecFilter",protocolCodecFilter); //配置NioSocketConnector处理器 SimpleClientHandler simpleClientHandler = new SimpleClientHandler(); connector.setHandler(simpleClientHandler); InetSocketAddress inetSocketAddress = new InetSocketAddress(ip,port); connector.connect(inetSocketAddress); log.info("=========SimpleClient is start============"); } }
client handler:
package mina.tcp.handler; import java.nio.charset.CharacterCodingException; import java.nio.charset.Charset; import java.nio.charset.CharsetDecoder; import java.nio.charset.CharsetEncoder; import org.apache.mina.core.buffer.IoBuffer; 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; /** * simple client handler * @author donald * 2017年5月19日 * 下午1:10:12 */ public class SimpleClientHandler extends IoHandlerAdapter { private final static Logger log = LoggerFactory.getLogger(SimpleClientHandler.class); private static final CharsetEncoder charsetEncoder= Charset.forName("UTF-8").newEncoder(); private static final CharsetDecoder charsetDecoder= Charset.forName("UTF-8").newDecoder(); public void messageReceived(IoSession session, Object message) throws Exception { String msg = (String) message; log.info("=========The message received from Server is:" + msg); } @Override public void sessionCreated(IoSession session) throws Exception { log.debug("=========Session Created..."); } @Override public void sessionOpened(IoSession session) throws CharacterCodingException { IoBuffer buffer = IoBuffer.allocate(1024); buffer.putString("Hello Server...\r\nI'm Client...\r\nclient test...", charsetEncoder); buffer.flip(); session.write(buffer); //我们可以在这里发送一个quit命令,当Server接受到quit命令时,关闭会话 /*buffer.clear(); buffer.putString("quit\r\n", charsetEncoder); buffer.flip(); session.write(buffer);*/ } @Override public void sessionIdle(IoSession session, IdleStatus status) throws Exception { log.debug(session + "=========Session Idle..."); } @Override public void exceptionCaught(IoSession session, Throwable cause) throws Exception { log.error(cause.getMessage()); cause.printStackTrace(); session.closeNow(); } @Override public void messageSent(IoSession session, Object message) throws Exception { log.debug("=========messageSent..."); } @Override public void sessionClosed(IoSession session) throws Exception { log.debug("=========Session Closed..."); } }
本实例中的handler的继承IoHandlerAdapter,在实际开发中,我们不需要实现所有方法,我们只需要实现关注的方法即可比如sessionOpened,
messageReceived,exceptionCaught,sessionClosed。
启动server,client控制台输出:
server:
[INFO ] 2017-05-21 10:46:31 mina.tcp.main.SimpleServer =========SimpleServer is start============
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter CREATED
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========Session Created...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter OPENED
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========Session Opened...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:Hello Server...
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:I'm Client...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========messageSent...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleServerHandler =========messageSent...
[INFO ] 2017-05-21 10:46:53 org.apache.mina.filter.logging.LoggingFilter IDLE
[DEBUG] 2017-05-21 10:46:53 mina.tcp.handler.SimpleServerHandler (0x00000001: nio socket, server, /192.168.126.135:60519 => /192.168.126.135:9122)=========Session Idle...
client:
[INFO ] 2017-05-21 10:46:43 mina.tcp.main.SimpleClient =========SimpleClient is start============
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter CREATED
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========Session Created...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter OPENED
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========messageSent...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:Hello Client...
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:I'm Server...
[INFO ] 2017-05-21 10:46:43 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 10:46:43 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:server test...Hello Client...
[INFO ] 2017-05-21 10:46:43 mina.tcp.handler.SimpleClientHandler =========The message received from Server is:I'm Server...
从上面的日志可以看出,LoggingFilter的输出在Handler日志前面,证明了,IoService发送的数据要经过IoFilter层,再由IoHandler处理。由于我们用的是TextLineCodecFactory(按行发送与接收数据),从日志输出来,client将多行数据一次发送,而server将发送过来的多行数据分行读取;client发送的为
Hello Server...\r\nI'm Client...\r\nclient test...
而server收到的为
1.Hello Server...
2.I'm Client...
这两行后面的client test...没有收到,证明TextLineCodecFactory是按行发送与接收数据,不到一行数据,不解析数据。
由于server接受了两次client发送过来的数据,并回复
Hello Client...\r\nI'm Server...\r\nserver test...
从client的输出来看,
第一次接收事件:
Hello Client...
I'm Server...
第二次接收事件:
server test...Hello Client...
I'm Server...
从上面可以看出,第一次没有解析完的数据留在缓冲区中,与下一次接收的数据合并处理。
整个过程:
client发生一次发送事件,server一次接收事件,多次调用handler处理行数据,并产生了多次发送事件,client相应的产生多次接收事件,并将上一次没有解析完的数据,与下一次接收的数据合并处理。
过滤器:
再来测试一下IoFilter,编写测试IoFilter
package mina.tcp.filter; import org.apache.mina.core.filterchain.IoFilter; import org.apache.mina.core.filterchain.IoFilterChain; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.core.write.WriteRequest; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * 测试过滤器 * @author donald * 2017年5月19日 * 上午8:59:29 */ public class TestFilter implements IoFilter { private static final Logger log = LoggerFactory.getLogger(TestFilter.class); @Override public void onPreAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { log.debug("$$$$$$$$onPreAdd..."); } @Override public void onPostAdd(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { log.debug("$$$$$$$$onPostAdd..."); } @Override public void init() throws Exception { log.debug("$$$$$$$$init..."); } @Override public void filterWrite(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { log.debug("$$$$$$$$filterWrite..."); nextFilter.filterWrite(session, writeRequest); } @Override public void sessionCreated(NextFilter nextFilter, IoSession session) throws Exception { log.debug("$$$$$$$$sessionCreated..."); nextFilter.sessionCreated(session); } @Override public void sessionIdle(NextFilter nextFilter, IoSession session, IdleStatus status) throws Exception { log.debug("$$$$$$$$sessionIdle..."); nextFilter.sessionIdle(session, status); } @Override public void sessionOpened(NextFilter nextFilter, IoSession session) throws Exception { log.debug("$$$$$$$$sessionOpened..."); nextFilter.sessionOpened(session); } @Override public void messageReceived(NextFilter nextFilter, IoSession session, Object message) throws Exception { log.debug("$$$$$$$$messageReceived..."); nextFilter.messageReceived(session, message); } @Override public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception { log.debug("$$$$$$$$messageSent..."); nextFilter.messageSent(session, writeRequest); } @Override public void exceptionCaught(NextFilter nextFilter, IoSession session, Throwable cause) throws Exception { log.debug("$$$$$$$$exceptionCaught..."); nextFilter.exceptionCaught(session, cause); } @Override public void onPostRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { log.debug("$$$$$$$$onPostRemove..."); } @Override public void onPreRemove(IoFilterChain parent, String name, NextFilter nextFilter) throws Exception { log.debug("$$$$$$$$onPreRemove..."); } @Override public void inputClosed(NextFilter arg0, IoSession arg1) throws Exception { log.debug("$$$$$$$$inputClosed..."); } @Override public void filterClose(NextFilter nextFilter, IoSession session) throws Exception { log.debug("$$$$$$$$filterClose..."); nextFilter.filterClose(session); } @Override public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception { log.debug("$$$$$$$$sessionClosed..."); nextFilter.sessionClosed(session); } @Override public void destroy() throws Exception { log.debug("$$$$$$$$destroy..."); } }
注意在filter*和session*及exceptionCaught方法调用时,要NextFilter相应方法,这一点和web的Filter#doFilter相似。
修改上一个实例中的Server端:
import java.io.IOException; import java.net.InetSocketAddress; import java.nio.charset.Charset; 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.codec.textline.LineDelimiter; import org.apache.mina.filter.codec.textline.TextLineCodecFactory; import org.apache.mina.filter.logging.LoggingFilter; import org.apache.mina.filter.util.ReferenceCountingFilter; import org.apache.mina.transport.socket.SocketSessionConfig; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import mina.tcp.filter.TestFilter; import mina.tcp.handler.SimpleServerHandler; /** * Simple Server With TestFilter * @author donald * 2017年5月19日 * 上午8:59:37 */ public class SimpleServerWithTestFilter { private static final Logger log = LoggerFactory.getLogger(SimpleServerWithTestFilter.class); private static final String ip = "192.168.126.135"; private static final int port = 9122; private static final int readBufferSize = 2048; private static final int idleTime = 10; private static final Charset charset = Charset.forName("UTF-8"); public static void main(String[] args) throws IOException { IoAcceptor acceptor=new NioSocketAcceptor(); //配置socket会话 SocketSessionConfig socketSessionConfig = (SocketSessionConfig) acceptor.getSessionConfig(); socketSessionConfig.setReadBufferSize(readBufferSize); socketSessionConfig.setIdleTime(IdleStatus.BOTH_IDLE,idleTime); //配置过滤器 DefaultIoFilterChainBuilder defaultIoFilterChainBuilder = acceptor.getFilterChain(); LoggingFilter loggingFilter = new LoggingFilter(); defaultIoFilterChainBuilder.addLast("loggingFilter", loggingFilter); TextLineCodecFactory textLineCodecFactory = new TextLineCodecFactory(charset,LineDelimiter.WINDOWS.getValue(), LineDelimiter.WINDOWS.getValue()); ProtocolCodecFilter protocolCodecFilter = new ProtocolCodecFilter(textLineCodecFactory); defaultIoFilterChainBuilder.addLast("protocolCodecFilter",protocolCodecFilter); TestFilter testFilter = new TestFilter(); ReferenceCountingFilter referenceCountingFilter = new ReferenceCountingFilter(testFilter); defaultIoFilterChainBuilder.addLast("testFilter",referenceCountingFilter); //配置NioSocketAcceptor处理器 SimpleServerHandler simpleServerHandler = new SimpleServerHandler(); acceptor.setHandler(simpleServerHandler); InetSocketAddress inetSocketAddress = new InetSocketAddress(ip,port); acceptor.bind(inetSocketAddress); log.info("=========SimpleServer is start============"); } }
启动SimpleServerWithTestFilter,server,及上例中的client,
SimpleServerWithTestFilter控制台输出:
[INFO ] 2017-05-21 00:51:54 mina.tcp.main.SimpleServerWithTestFilter =========SimpleServer is start============
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$init...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$onPreAdd...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$onPostAdd...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter CREATED
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$sessionCreated...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========Session Created...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter OPENED
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$sessionOpened...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========Session Opened...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter RECEIVED: HeapBuffer[pos=0 lim=46 cap=2048: 48 65 6C 6C 6F 20 53 65 72 76 65 72 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 00:52:00 org.apache.mina.filter.codec.ProtocolCodecFilter Processing a MESSAGE_RECEIVED for session 1
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageReceived...
[INFO ] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:Hello Server...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$filterWrite...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageReceived...
[INFO ] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========The message received from Client is:I'm Client...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$filterWrite...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageSent...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========messageSent...
[INFO ] 2017-05-21 00:52:00 org.apache.mina.filter.logging.LoggingFilter SENT: HeapBuffer[pos=0 lim=46 cap=1024: 48 65 6C 6C 6F 20 43 6C 69 65 6E 74 2E 2E 2E 0D...]
[DEBUG] 2017-05-21 00:52:00 mina.tcp.filter.TestFilter $$$$$$$$messageSent...
[DEBUG] 2017-05-21 00:52:00 mina.tcp.handler.SimpleServerHandler =========messageSent...
从日志输出来看,init,onPreAdd,onPostAdd事件在会话创建时已经发生,这些方法主要用于初始化过滤器,添加过滤器到IoService
的过滤链时触发。会话事件顺序CREATED-》OPENED-》RECEIVED。从上面的日志输出可以看出整个过程的处理顺序为,
SimpleServerWithTestFilter-》LoggingFilter-》TestFilter-》ProtocolCodecFilter-》SimpleServerHandler,
过滤器的顺序默认为添加的顺序。在每次过滤器捕捉到接收数据事件,都将调用filterWrite方法。
- lib.rar (1022.7 KB)
- 下载次数: 4
发表评论
-
Mina 报文连接器(NioDatagramConnector)
2017-06-14 08:46 1420Mina 抽象Polling连接器(A ... -
Mina 报文监听器NioDatagramAcceptor二(发送会话消息等)
2017-06-13 16:01 1544Mina 报文监听器NioDatagramAcceptor一( ... -
Mina 报文监听器NioDatagramAcceptor一(初始化,Io处理器)
2017-06-13 09:51 2578Mina Io监听器接口定义及抽象实现:http://dona ... -
Mina 报文通信简单示例
2017-06-12 09:01 2586MINA TCP简单通信实例:http://donald-dr ... -
Mina socket连接器(NioSocketConnector)
2017-06-12 08:37 4776Mina 抽象Polling连接器(AbstractPolli ... -
Mina 抽象Polling连接器(AbstractPollingIoConnector)
2017-06-11 21:29 1010Mina 连接器接口定义及抽象实现(IoConnector ) ... -
Mina 连接器接口定义及抽象实现(IoConnector )
2017-06-11 13:46 1835Mina IoService接口定义及抽象实现:http:// ... -
Mina socket监听器(NioSocketAcceptor)
2017-06-09 08:44 3424Mina IoService接口定义及抽象实现:http:// ... -
Mina 抽象polling监听器
2017-06-08 22:32 786Mina Io监听器接口定义及抽象实现:http://dona ... -
Mina Io监听器接口定义及抽象实现
2017-06-07 13:02 1352Mina IoService接口定义及抽象实现:http:// ... -
Mina IoService接口定义及抽象实现
2017-06-06 23:44 1200Mina IoHandler接口定义:http://donal ... -
Mina Nio会话(Socket,DataGram)
2017-06-06 12:53 1210Mina Socket会话配置:http://donald-d ... -
Mina 抽象Io会话
2017-06-05 22:45 1017Mina Io会话接口定义:http://donald-dra ... -
Mina Io会话接口定义
2017-06-04 23:15 1170Mina Nio处理器:http://donald-drape ... -
Mina Nio处理器
2017-06-04 22:19 745Mina Io处理器抽象实现:http://donald-dr ... -
Mina Io处理器抽象实现
2017-06-03 23:52 1151Mina 过滤链抽象实现:http://donald-drap ... -
Mina IoHandler接口定义
2017-06-01 21:30 1736Mina 过滤链抽象实现:http://donald-drap ... -
MINA 多路复用协议编解码器工厂二(多路复用协议解码器)
2017-06-01 12:52 2279MINA 多路复用协议编解码器工厂一(多路复用协议编码器): ... -
MINA 多路复用协议编解码器工厂一(多路复用协议编码器)
2017-05-31 22:22 1873MINA 多路分离解码器实例:http://donald-dr ... -
Mina 累计协议解码器
2017-05-31 00:09 1234MINA 编解码器实例:http://donald-drape ...
相关推荐
这是一个有关Mina在Java通信中运用的简单的入门实例,MIna自带一种触发机制,无需再开线程等待收发数据。这个实例中有客户端和服务端,与软件TCPUDPDbg进行文字通话测试。用的时候注意添加Mina包,此实例中用到的是...
本实例将深入探讨如何使用Mina进行TCP通信。 首先,Mina的核心是它的事件驱动模型,通过异步I/O处理,允许开发者以低延迟和高并发性构建网络服务。在TCP实例中,我们将涉及到以下几个关键概念: 1. **Acceptor**:...
实战部分,我们来看一个简单的mina TCP通信示例。首先创建一个Acceptor,监听特定端口,然后创建一个处理数据的Handler。当客户端连接时,mina会触发SessionCreated事件,我们可以在Handler中处理这个事件,进行相应...
《MINA网络通信实例解析》 MINA(Multipurpose Infrastructure for Network Applications)是Apache软件基金会的一个开源项目,它提供了一个高度可扩展且跨平台的网络应用程序框架,主要用于简化开发高性能和高可用...
本实例将探讨如何使用MINA实现客户端与服务端的通信。 MINA框架是Apache软件基金会的一个项目,它提供了基于NIO(Non-blocking I/O)的网络编程接口。NIO是一种在Java中实现高并发、低延迟I/O操作的方法,特别适合...
本实例将探讨如何将队列与MINA通信框架结合,以实现高效、可靠的网络服务。以下是关于这两个概念及其结合使用的详细说明。 **队列(Queue)** 队列是一种数据结构,遵循先进先出(FIFO,First In First Out)原则...
总结一下,这个"Mina开发实例"涵盖了如何使用Apache Mina创建服务端和客户端,通过Maven构建项目,并实现长连接通信。通过学习和实践这个DEMO,开发者可以掌握Mina的基本用法,为构建高性能、高并发的网络应用打下...
本入门实例将带你了解如何使用Mina进行基本的网络通信。 首先,我们从环境配置开始。这个实例要求使用Maven作为项目构建工具,因此你需要确保已经安装了Maven,并且在项目中设置了正确的`pom.xml`文件。在`pom.xml`...
在这个实例中,我们将深入探讨如何利用Apache Mina实现TCP的长连接和短连接。 首先,TCP(传输控制协议)是互联网上广泛使用的面向连接的协议,它保证了数据的可靠传输。TCP连接分为两种类型:长连接和短连接。 1....
它提供了一个抽象的、事件驱动的异步API,使Java NIO在各种传输协议(如TCP/IP,UDP/IP协议等)下快速高效开发。 Apache Mina也称为: NIO框架 客户端/服务端框架(典型的C/S架构) 网络套接字(networking...
在IT行业中,网络通信是至关重要的一个领域,而Apache Mina作为一个高性能、事件驱动的网络应用框架,广泛应用于TCP、UDP等协议的开发。本文将深入探讨Mina框架中的长连接与短连接,并通过提供的Minaclient和...
基于 TCP/IP、UDP/IP协议栈的通信框架 支持串口和虚拟机内部的管道等传输方式 Mina 可以帮助我们快速开发高性能、高扩展性的网络通信应用 Mina 提供了事件驱动、异步操作(JAVA NIO 作为底层支持)的编程模型 本...
Mina2(全称Apache MINA,Multipurpose Infrastructure for Network Applications)是一个高性能、事件驱动的网络应用程序框架,主要应用于开发网络通信应用,如TCP/IP和UDP/IP协议栈。它由Java编写,提供了一种简化...
标题中提到的"mina2服务端客户端实例"是指使用Apache MINA 2版本创建的一个工作示例,该示例包含了服务端和客户端的完整代码,旨在帮助开发者理解如何在实际项目中运用MINA进行网络通信。通过导入Eclipse这样的集成...
在本实例中,可能自定义了一个简单的编解码器,以适应特定的通信协议,可能是基于固定长度或基于特定分隔符的数据包。 此外,“工具类”可能包含了处理网络操作辅助方法,例如数据包的序列化和反序列化,或者错误...
Apache MINA(Multipurpose Infrastructure for Network Applications)是一个开源框架,主要设计用于简化网络应用程序的开发,尤其是基于TCP和UDP协议的应用。它提供了高度可扩展和高性能的非阻塞I/O模型,使得...
总结,MINA框架提供了强大的工具,使得开发TCP客户端变得简单而高效,特别是对于需要长连接的应用,如网络游戏、实时通信系统等。通过理解并实践上述步骤,你可以构建出稳定、高效的TCP客户端应用程序。记住,MINA的...
这个实例是基于Mina框架构建的一个应用程序,名为"BTUSimulator",它可能是用来模拟某种网络通信或者服务的。让我们深入探讨一下Mina框架以及如何在实际项目中应用它。 **Apache Mina框架详解** Mina(Minimum ...
通过上述步骤,我们可以构建一个简单的MINA HTTP服务器,它可以接收HTTP请求并返回响应。这只是一个基础实例,实际应用中可能需要处理更复杂的场景,比如HTTPS安全连接、WebSocket双向通信等。 总而言之,Apache ...