• NIO框架Mina学习


    前言:

          找了篇文章看了看,nio框架数Mina用的最多!

    代码:

    服务端:

    package com.mina;
    
    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 = 9999;
        
        public static void main(String[] args) throws Exception {
        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());
            acceptor.getSessionConfig().setReadBufferSize( 2048 );
            acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, 10 );
            acceptor.bind( new InetSocketAddress(PORT) );
            
        }
    }
    package com.mina;
    
    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{
    
         @Override
            public void exceptionCaught( IoSession session, Throwable cause ) throws Exception
            {
                cause.printStackTrace();
            }
    
            @Override
            public void messageReceived( IoSession session, Object message ) throws Exception
            {
                String str = message.toString();
                if( str.trim().equalsIgnoreCase("quit") ) {
                    session.closeNow();
                    return;
                }
    
                Date date = new Date();
                session.write( date.toString() );
                System.out.println("Message written...");
            }
    
            @Override
            public void sessionIdle( IoSession session, IdleStatus status ) throws Exception
            {
                System.out.println( "IDLE " + session.getIdleCount( status ));
            }
        
        
    }

    都是官网的代码,没有客户端,所以用Socket写一个客户端:

    package com.my.socket;
    
    import java.net.*;
    import java.io.*;
    
    public class Client2 {
        Socket s = null;
        PrintWriter pw = null;
        BufferedReader br1 = null;
        BufferedReader br2 = null;
    
        public Client2() {
            try {
                // Socket()方法可以连接某个服务器,127.0.0.1表示服务器的IP,9999是该服务器的端口号
                s = new Socket("127.0.0.1", 9999);
                while (true) {
                    // 连接成功,就可以发送数据给服务器
                    // 从控制台读入数据
                    System.out.print("从控制台输入:");
                    br1 = new BufferedReader(new InputStreamReader(System.in));
                    String str = br1.readLine();
                    // 通过PrintWriter向s写数据,true表示即时刷新
                    pw = new PrintWriter(s.getOutputStream(), true);
                    pw.println(str);
                    if (str.equals("byebye")) {
                        System.out.println("客户端关闭连接");
                        break;
                    }
    
                    // 从服务端接收消息
                    br2 = new BufferedReader(new InputStreamReader(
                            s.getInputStream()));
                    System.out.println("从服务器接收的消息是:" + br2.readLine());
                }
    
            } catch (UnknownHostException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                try {
                    // 关闭资源
                    if (pw != null) {
                        pw.close();
                    }
                    if (br2 != null) {
                        br2.close();
                    }
                    if (br1 != null) {
                        br1.close();
                    }
                    if (s != null) {
                        s.close();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    
        public static void main(String[] args) {
            Client2 c2 = new Client2();
        }
    
    }

    好像没体现出来哪好。出来代码简单点!

  • 相关阅读:
    Python基础:条件判断与循环的两个要点
    oozie note
    Dynamics CRM2013 Server2012R2下IFD部署遇到There is already a listener on IP endpoint的解决方法
    监控系统的多协议直播(RTSP RTMP HTTP Live Streaming)
    易迅,生的霸气,死的窝囊
    js中的splice方法和slice方法简单总结
    JAVA虚拟机的安装以及JAVA的环境配置
    JS函数种类详解
    IDEA多线程调试设置
    Java中的HashMap源码记录以及并发环境的几个问题
  • 原文地址:https://www.cnblogs.com/liangblog/p/5895834.html
Copyright © 2020-2023  润新知