java NIO理解

认识NIO

NIO 是一种同步非阻塞的 IO 模型。同步是指线程不断轮询 IO 事件是否就绪,非阻塞是指线程在等待 IO 的时候,可以同时做其他任务。同步的核心就是 Selector,Selector 代替了线程本身轮询 IO 事件,避免了阻塞同时减少了不必要的线程消耗;非阻塞的核心就是通道和缓冲区,当 IO 事件就绪时,可以通过写道缓冲区,保证 IO 的成功,而无需线程阻塞式地等待。

Buffer:

    为什么说NIO是基于缓冲区的IO方式呢?因为,当一个链接建立完成后,IO的数据未必会马上到达,为了当数据到达时能够正确完成IO操作,在BIO(阻塞IO)中,等待IO的线程必须被阻塞,以全天候地执行IO操作。为了解决这种IO方式低效的问题,引入了缓冲区的概念,当数据到达时,可以预先被写入缓冲区,再由缓冲区交给线程,因此线程无需阻塞地等待IO。

通道:

    当执行:SocketChannel.write(Buffer),便将一个 buffer 写到了一个通道中。如果说缓冲区还好理解,通道相对来说就更加抽象。网上博客难免有写不严谨的地方,容易使初学者感到难以理解。

    引用 Java NIO 中权威的说法:通道是 I/O 传输发生时通过的入口,而缓冲区是这些数 据传输的来源或目标。对于离开缓冲区的传输,您想传递出去的数据被置于一个缓冲区,被传送到通道。对于传回缓冲区的传输,一个通道将数据放置在您所提供的缓冲区中。

    例如 有一个服务器通道 ServerSocketChannel serverChannel,一个客户端通道 SocketChannel clientChannel;服务器缓冲区:serverBuffer,客户端缓冲区:clientBuffer。

    当服务器想向客户端发送数据时,需要调用:clientChannel.write(serverBuffer)。当客户端要读时,调用 clientChannel.read(clientBuffer)

    当客户端想向服务器发送数据时,需要调用:serverChannel.write(clientBuffer)。当服务器要读时,调用 serverChannel.read(serverBuffer)

    这样,通道和缓冲区的关系似乎更好理解了。在实践中,未必会出现这种双向连接的蠢事(然而这确实存在的,后面的内容还会涉及),但是可以理解为在NIO中:如果想将Data发到目标端,则需要将存储该Data的Buffer,写入到目标端的Channel中,然后再从Channel中读取数据到目标端的Buffer中。

Selector:

    通道和缓冲区的机制,使得线程无需阻塞地等待IO事件的就绪,但是总是要有人来监管这些IO事件。这个工作就交给了selector来完成,这就是所谓的同步。

    Selector允许单线程处理多个 Channel。如果你的应用打开了多个连接(通道),但每个连接的流量都很低,使用Selector就会很方便。

    要使用Selector,得向Selector注册Channel,然后调用它的select()方法。这个方法会一直阻塞到某个注册的通道有事件就绪,这就是所说的轮询。一旦这个方法返回,线程就可以处理这些事件。

    Selector中注册的感兴趣事件有:

  • OP_ACCEPT

  • OP_CONNECT 

  • OP_READ 

  • OP_WRITE

优化:

    一种优化方式是:将Selector进一步分解为Reactor,将不同的感兴趣事件分开,每一个Reactor只负责一种感兴趣的事件。这样做的好处是:1、分离阻塞级别,减少了轮询的时间;2、线程无需遍历set以找到自己感兴趣的事件,因为得到的set中仅包含自己感兴趣的事件。

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.nio.charset.CharsetDecoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;


public class ServerSocket {
       private int port = 6001;
       //解码buffer
       private CharsetDecoder decode = Charset.forName("UTF-8").newDecoder();
       /*发送数据缓冲区*/
       private ByteBuffer sBuffer = ByteBuffer.allocate(1024);
       /*接受数据缓冲区*/
       private ByteBuffer rBuffer = ByteBuffer.allocate(1024);
       /*映射客户端channel */
       private Map<String, SocketChannel> clientsMap = new HashMap<String, SocketChannel>(); 
       private Selector selector;
       private SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss", java.util.Locale.US);

       public ServerSocket(){
           try {
               init();
               listen();
           } catch (Exception e) {
               e.printStackTrace();
           }
       }
       private void init() throws Exception{
           /* 
            *启动服务器端,配置为非阻塞,绑定端口,注册accept事件 
            *ACCEPT事件:当服务端收到客户端连接请求时,触发该事件 
            */  
           ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();  
           serverSocketChannel.configureBlocking(false);  
           java.net.ServerSocket serverSocket = serverSocketChannel.socket();  
           serverSocket.bind(new InetSocketAddress(port));  
           selector = Selector.open();  
           serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);  
           System.out.println("server start on port:"+port);  
       }

       /** 
        * 服务器端轮询监听,select方法会一直阻塞直到有相关事件发生或超时 
        */  
       private void listen(){

           while (true) {
               try {
                   selector.select();//返回值为本次触发的事件数
               System.out.println("返回值为本次触发的事件数"+selector.select());
                   Set<SelectionKey> selectionKeys = selector.selectedKeys();  
                   for(SelectionKey key : selectionKeys){
                       handle(key);
                       System.out.println("监听循环");
                   }
                   selectionKeys.clear();//清除处理过的事件 
               } catch (Exception e) {
                   e.printStackTrace();  
                   break;  
               }  
           }
       }

       /**
        * 处理不同的事件 
        */ 
       private void handle(SelectionKey selectionKey) throws IOException { 

           ServerSocketChannel server = null;
           SocketChannel client = null;
           String receiveText=null;
           int count=0;
           if (selectionKey.isAcceptable()) {
               /* 
                * 客户端请求连接事件 
                * serversocket为该客户端建立socket连接,将此socket注册READ事件,监听客户端输入 
                * READ事件:当客户端发来数据,并已被服务器控制线程正确读取时,触发该事件 
                */  
               server = (ServerSocketChannel) selectionKey.channel();
               client = server.accept();
               client.configureBlocking(false);
               client.register(selector, SelectionKey.OP_READ);
           } else if (selectionKey.isReadable()) {
               /*
                * READ事件,收到客户端发送数据,读取数据后继续注册监听客户端 
                */
               client = (SocketChannel) selectionKey.channel();
               rBuffer.clear();
               count = client.read(rBuffer);
               if (count > 0) {
                   rBuffer.flip();
                   receiveText = decode.decode(rBuffer.asReadOnlyBuffer()).toString();
                   System.out.println(client.toString()+":"+receiveText);
                   sBuffer.clear();
                   sBuffer.put((sdf.format(new Date())+"服务器收到你的消息").getBytes("UTF-8"));
                   sBuffer.flip();
                   client.write(sBuffer);
                   dispatch(client, receiveText);
                   client = (SocketChannel) selectionKey.channel();
                   client.register(selector, SelectionKey.OP_READ);
               }  
           }   
       }  

       /** 
        * 把当前客户端信息 推送到其他客户端 
        */
       private void dispatch(SocketChannel client,String info) throws IOException{  

           Socket s = client.socket();  
           String name = "["+s.getInetAddress().toString().substring(1)+":"+Integer.toHexString(client.hashCode())+"]";
           System.out.println("name=="+name);
           if(!clientsMap.isEmpty()){
               for(Map.Entry<String, SocketChannel> entry : clientsMap.entrySet()){
                   SocketChannel temp = entry.getValue();
                   if(!client.equals(temp)){
                       sBuffer.clear();
                       sBuffer.put((name+":"+info).getBytes("UTF-8"));
                       sBuffer.flip();
                       //输出到通道
                       temp.write(sBuffer);
                   }
               }
           }
           clientsMap.put(name, client);
       }
       
       public static void main(String[] args) throws IOException {  
          new ServerSocket();  
       }  
     

}
客户端处理

/**
 * Created by zhonghuan on 17/5/25.
 */
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.nio.charset.Charset;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

import com.sun.org.apache.xerces.internal.impl.io.UTF8Reader;
import com.sun.org.apache.xerces.internal.impl.xpath.regex.ParseException;
import sun.text.normalizer.UTF16;


public class ClientNIO {
    /*发送数据缓冲区*/
    private static ByteBuffer sBuffer = ByteBuffer.allocate(1024);
    /*接受数据缓冲区*/
    private static ByteBuffer rBuffer = ByteBuffer.allocate(1024);
    /*服务器端地址*/
    private InetSocketAddress SERVER;
    private Selector selector;
    private SocketChannel client;
    private String receiveText;
    private String sendText;
    private int count=0;
    private Charset charset = Charset.forName("UTF-8");
    private SimpleDateFormat sdf = new SimpleDateFormat("YYYY-MM-dd HH:mm:ss", java.util.Locale.US);

    public ClientNIO(){

        SERVER = new InetSocketAddress("localhost", 6001);
        init();
    }
    /**
     *
     */
    public void init(){

        try {
           /*
            * 客户端向服务器端发起建立连接请求
            */
            SocketChannel socketChannel = SocketChannel.open();
            socketChannel.configureBlocking(false);
            selector = Selector.open();
            socketChannel.register(selector, SelectionKey.OP_CONNECT);
            socketChannel.connect(SERVER);
           /*
            * 轮询监听客户端上注册事件的发生
            */
            while (true) {
                selector.select();
                Set<SelectionKey> keySet = selector.selectedKeys();
                for(final SelectionKey key : keySet){
                    handle(key);
                }
                keySet.clear();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {

        new ClientNIO();
    }

    /**
     * @param selectionKey
     * @throws IOException
     * @throws ParseException
     */
    private void handle(SelectionKey selectionKey) throws IOException, ParseException{

        if (selectionKey.isConnectable()) {
           /*
            * 连接建立事件,已成功连接至服务器
            */
            client = (SocketChannel) selectionKey.channel();
            if (client.isConnectionPending()) {
                client.finishConnect();
                System.out.println("connect success !");
                sBuffer.clear();
                sBuffer.put((sdf.format(new Date())+" connected!").getBytes());
                sBuffer.flip();
                client.write(sBuffer);//发送信息至服务器
               /* 原文来自 站长网
                * 启动线程一直监听客户端输入,有信心输入则发往服务器端
                * 因为输入流是阻塞的,所以单独线程监听
                */
                new Thread(){
                    @Override
                    public void run() {
                        while(true){
                            try {
                                sBuffer.clear();
                                InputStreamReader input = new InputStreamReader(System.in);
                                BufferedReader br = new BufferedReader(input);
                                sendText = br.readLine();
                               /*
                                * 未注册WRITE事件,因为大部分时间channel都是可以写的
                                */
                                sBuffer.put(charset.encode(sendText.trim()));
                                sBuffer.flip();
                                client.write(sBuffer);
                            } catch (IOException e) {
                                e.printStackTrace();
                                break;
                            }
                        }
                    }
                }.start();
            }
            //注册读事件
            client.register(selector, SelectionKey.OP_READ);
        } else if (selectionKey.isReadable()) {
           /*
            * 读事件触发
            * 有从服务器端发送过来的信息,读取输出到屏幕上后,继续注册读事件
            * 监听服务器端发送信息
            */
            client = (SocketChannel) selectionKey.channel();
            count=client.read(rBuffer);
            if(count>0){
                receiveText = new String( rBuffer.array(),0,count,"UTF-8");
                System.out.println(receiveText);
                client = (SocketChannel) selectionKey.channel();
                client.register(selector, SelectionKey.OP_READ);
                rBuffer.clear();
            }
        }
    }

}







  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值