MINA经典入门例子----Time Server

    技术2024-12-02  21

     貌似java的IO、NIO的入门例子都有相关的Time Server Demo。本例为MINA官方Demo翻译过来而已。

      MINA百科:

       Apache MINA(Multipurpose Infrastructure for Network Applications) 是 Apache 组织一个较新的项目,它为开发高性能和高可用性的网络应用程序提供了非常便

         

    apache mina

    利的框架。当前发行的 MINA 版本支持基于 Java NIO 技术的 TCP/UDP 应用程序开发、串口通讯程序(只在最新的预览版中提供),MINA 所支持的功能也在进一步的扩展中。

      目前正在使用 MINA 的软件包括有:Apache Directory Project、AsyncWeb、AMQP(Advanced Message Queuing Protocol)、RED5 Server(Macromedia Flash Media RTMP)、ObjectRADIUS、Openfire 等等。

          目前最新版本为2.02 Release,官方网站为:http://mina.apache.org/。

          MINA框架的特点有:基于java NIO类库开发;采用非阻塞方式的异步传输;事件驱动;支持批量数据传输;支持TCP、UDP协议;控制反转的设计模式(支持Spring);采用优雅的松耦合架构;可灵活的加载过滤器机制;单元测试更容易实现;可自定义线程的数量,以提高运行于多处理器上的性能;采用回调的方式完成调用,线程的使用更容易。      MINA框架的常用类 类NioSocketAcceptor用于创建服务端监听; 类NioSocketConnector用于创建客户端连接; 类IoSession用来保存会话属性和发送消息; 类IoHandlerAdapter用于定义业务逻辑,常用的方法有: 方法 定义 sessionCreated() 当会话创建时被触发 sessionOpened() 当会话开始时被触发 sessionClosed() 当会话关闭时被触发 sessionIdle() 当会话空闲时被触发 exceptionCaught() 当接口中其他方法抛出异常未被捕获时触发此方法 messageRecieved() 当接收到消息后被触发 messageSent() 当发送消息后被触发

          Time Server测试示例:

          测试环境:Eclipse,jdk1.6,所需jar包,slf4j-api-1.5.11.jar、slf4j-jdk14-1.5.2.jar、mina-core-2.0.2.jar。       1、服务器端:

          1)服务器Server代码:

    package org.apache.mina.example.gettingstarted.timeserver;

    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.TextLineCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketAcceptor;

    public class MinaTimeServer {private static final int PORT = 9123;

    public static void main(String[] args) throws IOException {// 创建服务器监听

    IoAcceptor acceptor = new NioSocketAcceptor();// 增加日志过滤器

    acceptor.getFilterChain().addLast( "logger", new LoggingFilter() );//增加编码过滤器

    acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter( new TextLineCodecFactory( Charset.forName( "UTF-8" ))));//指定业务逻辑处理器

    acceptor.setHandler( new TimeServerHandler() );

    // 设置buffer的长度

    acceptor.getSessionConfig().setReadBufferSize( 2048 );

    //设置连接超时时间acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );// 绑定端口

    acceptor.bind( new InetSocketAddress(PORT) );}}

     2)业务逻辑处理器代码:

    package org.apache.mina.example.gettingstarted.timeserver;

    import java.util.Date;

    import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;

    public class TimeServerHandler extends IoHandlerAdapter{

    //连接异常时处理方法@Overridepublic void exceptionCaught( IoSession session, Throwable cause ) throws Exception{cause.printStackTrace();}

    /*** 接收处理客户端消息

    */@Overridepublic void messageReceived( IoSession session, Object message ) throws Exception{String str = message.toString();if( str.trim().equalsIgnoreCase("quit") ) {session.close(true);return;}

    Date date = new Date();session.write( date.toString() );System.out.println("Message written...");}

    /*** 连接超时时处理方法

    */@Overridepublic void sessionIdle( IoSession session, IdleStatus status ) throws Exception{System.out.println( "IDLE " + session.getIdleCount( status ));}}

     

    2、客户端测试代码

    1)客户端代码

    package com.kdiller.mina;

    import java.net.InetSocketAddress;import java.nio.charset.Charset;

    import org.apache.mina.core.future.ConnectFuture;import org.apache.mina.filter.codec.ProtocolCodecFilter;import org.apache.mina.filter.codec.textline.TextLineCodecFactory;import org.apache.mina.filter.logging.LoggingFilter;import org.apache.mina.transport.socket.nio.NioSocketConnector;

    public class MinaTimeClient { public static void main(String[] args) {  // 创建客户端连接器.  NioSocketConnector connector = new NioSocketConnector();  connector.getFilterChain().addLast("logger", new LoggingFilter());  connector.getFilterChain().addLast(    "codec",    new ProtocolCodecFilter(new TextLineCodecFactory(Charset      .forName("UTF-8")))); // 设置编码过滤器  connector.setConnectTimeout(30);  connector.setHandler(new TimeClientHandler());// 设置事件处理器  ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",    9123));// 建立连接  cf.awaitUninterruptibly();// 等待连接创建完成  cf.getSession().write("hello");// 发送消息  cf.getSession().write("quit");// 发送消息  cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开  connector.dispose(); }}

    2)客户端处理器

    package com.kdiller.mina;

    import org.apache.mina.core.service.IoHandlerAdapter;import org.apache.mina.core.session.IdleStatus;import org.apache.mina.core.session.IoSession;

    public class TimeClientHandler extends IoHandlerAdapter { public TimeClientHandler() { }

     @Override public void messageReceived(IoSession session, Object message)   throws Exception {  System.out.println("messageReceived method was called!");  System.out.println(message);// 显示接收到的消息 }

     @Override public void exceptionCaught(IoSession session, Throwable cause)   throws Exception {  // TODO Auto-generated method stub  super.exceptionCaught(session, cause); }

     @Override public void messageSent(IoSession session, Object message) throws Exception {  // TODO Auto-generated method stub  super.messageSent(session, message);  System.out.println("messageSent method was called!");  System.out.println(message); }

     @Override public void sessionClosed(IoSession session) throws Exception {  // TODO Auto-generated method stub  super.sessionClosed(session);  System.out.println("sessionClosed method was called!"); }

     @Override public void sessionCreated(IoSession session) throws Exception {  // TODO Auto-generated method stub  super.sessionCreated(session);  System.out.println("sessionCreated method was called!"); }

     @Override public void sessionIdle(IoSession session, IdleStatus status)   throws Exception {  // TODO Auto-generated method stub  super.sessionIdle(session, status); }

     @Override public void sessionOpened(IoSession session) throws Exception {  // TODO Auto-generated method stub  super.sessionOpened(session);  System.out.println("sessionOpened method was called!"); } }

     

    最新回复(0)