NIO框架Mina学习

2022-02-09 16:20:18 浏览数 (3)

前言:

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

代码:

服务端:

代码语言:javascript复制
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) );
        
    }
}
代码语言:javascript复制
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写一个客户端:

代码语言:javascript复制
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();
    }

}

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

0 人点赞