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


    原文地址 http://blog.sina.com.cn/s/blog_720bdf0501010b8r.html

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

      MINA百科:

       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 等等。

          目前最新版本为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)业务逻辑处理器代码:

     1 package org.apache.mina.example.gettingstarted.timeserver;
     2 
     3 import java.util.Date;
     4 
     5 import org.apache.mina.core.service.IoHandlerAdapter;
     6 import org.apache.mina.core.session.IdleStatus;
     7 import org.apache.mina.core.session.IoSession;
     8 
     9 public class TimeServerHandler extends IoHandlerAdapter
    10 {
    11 
    12 //连接异常时处理方法
    13 @Override
    14 public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
    15 {
    16 cause.printStackTrace();
    17 }
    18 
    19 
    20 @Override
    21 public void messageReceived( IoSession session, Object message ) throws Exception
    22 {
    23 String str = message.toString();
    24 
    25 if( str.trim().equalsIgnoreCase("quit") ) {
    26 session.close(true);
    27 return;
    28 }
    29 
    30 Date date = new Date();
    31 session.write( date.toString() );
    32 System.out.println("Message written...");
    33 }
    34 
    35 
    36 @Override
    37 public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
    38 {
    39 System.out.println( "IDLE " + session.getIdleCount( status ));
    40 }
    41 }
    View Code

    2、客户端测试代码

    1)客户端代码

     1 package com.kdiller.mina;
     2 
     3 import java.net.InetSocketAddress;
     4 import java.nio.charset.Charset;
     5 
     6 import org.apache.mina.core.future.ConnectFuture;
     7 import org.apache.mina.filter.codec.ProtocolCodecFilter;
     8 import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
     9 import org.apache.mina.filter.logging.LoggingFilter;
    10 import org.apache.mina.transport.socket.nio.NioSocketConnector;
    11 
    12 public class MinaTimeClient {
    13  public static void main(String[] args) {
    14   // 创建客户端连接器.
    15   NioSocketConnector connector = new NioSocketConnector();
    16   connector.getFilterChain().addLast("logger", new LoggingFilter());
    17   connector.getFilterChain().addLast(
    18     "codec",
    19     new ProtocolCodecFilter(new TextLineCodecFactory(Charset
    20       .forName("UTF-8")))); // 设置编码过滤器
    21   connector.setConnectTimeout(30);
    22   connector.setHandler(new TimeClientHandler());// 设置事件处理器
    23   ConnectFuture cf = connector.connect(new InetSocketAddress("127.0.0.1",
    24     9123));// 建立连接
    25   cf.awaitUninterruptibly();// 等待连接创建完成
    26   cf.getSession().write("hello");// 发送消息
    27   cf.getSession().write("quit");// 发送消息
    28   cf.getSession().getCloseFuture().awaitUninterruptibly();// 等待连接断开
    29   connector.dispose();
    30  }
    31 }

    2)客户端处理器

     1 package com.kdiller.mina;
     2 
     3 import org.apache.mina.core.service.IoHandlerAdapter;
     4 import org.apache.mina.core.session.IdleStatus;
     5 import org.apache.mina.core.session.IoSession;
     6 
     7 public class TimeClientHandler extends IoHandlerAdapter {
     8  public TimeClientHandler() {
     9  }
    10 
    11  @Override
    12  public void messageReceived(IoSession session, Object message)
    13    throws Exception {
    14   System.out.println("messageReceived method was called!");
    15   System.out.println(message);// 显示接收到的消息
    16  }
    17 
    18  @Override
    19  public void exceptionCaught(IoSession session, Throwable cause)
    20    throws Exception {
    21   // TODO Auto-generated method stub
    22   super.exceptionCaught(session, cause);
    23  }
    24 
    25  @Override
    26  public void messageSent(IoSession session, Object message) throws Exception {
    27   // TODO Auto-generated method stub
    28   super.messageSent(session, message);
    29   System.out.println("messageSent method was called!");
    30   System.out.println(message);
    31  }
    32 
    33  @Override
    34  public void sessionClosed(IoSession session) throws Exception {
    35   // TODO Auto-generated method stub
    36   super.sessionClosed(session);
    37   System.out.println("sessionClosed method was called!");
    38  }
    39 
    40  @Override
    41  public void sessionCreated(IoSession session) throws Exception {
    42   // TODO Auto-generated method stub
    43   super.sessionCreated(session);
    44   System.out.println("sessionCreated method was called!");
    45  }
    46 
    47  @Override
    48  public void sessionIdle(IoSession session, IdleStatus status)
    49    throws Exception {
    50   // TODO Auto-generated method stub
    51   super.sessionIdle(session, status);
    52  }
    53 
    54  @Override
    55  public void sessionOpened(IoSession session) throws Exception {
    56   // TODO Auto-generated method stub
    57   super.sessionOpened(session);
    58   System.out.println("sessionOpened method was called!");
    59  }
    60  
    61 }
  • 相关阅读:
    BOM和DOM
    js
    前端css
    html介绍
    线程锁&&信号量&&GIL&&线程定时器&&进程池与线程池&&协程
    对于数据库的操作以及配置
    string 迭代器
    递归
    python 操作mysql数据库
    Python编辑器IDLE傻瓜入门
  • 原文地址:https://www.cnblogs.com/dengmj/p/4719635.html
Copyright © 2020-2023  润新知