java.nio异步线程安全的IO

BIO 方式使得整个处理过程和链接是绑定的,只要链接创建,不管客户端是否有消息发送,都要进行等待处理,必定程度上浪费了服务器端的硬件资源,所以就有了 NIO 方式。Java 对于 NIO 方式的支持是经过 Channel和 Selector 方式来实现,采用的方法为向 Channel注册感兴趣的事件,而后经过 Selector 来获取到发生了事件的 key,如发生了相应的事件,则进行相应的处理,不然则不作任何处理,是典型的Reactor 模式,按照这样的方式,就不用像 BIO 方式同样,即便在没有消息的状况下也须要占据一个线程来阻塞读取消息,从而提高服务器的使用效率, 为实现 TCP/IP+NIO 方式的系统间通信, Java 提供了 SocketChannel和 ServerSocketChannel两个关键的类,网络 IO 的操做则改成经过ByteBuffer 来实现,具体的基于 java实现TCP/IP+NIO 方式的通信的方法以下所示。java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
package  com.flyoung;
 
import  java.io.IOException;
import  java.net.InetSocketAddress;
import  java.net.ServerSocket;
import  java.nio.ByteBuffer;
import  java.nio.channels.SelectionKey;
import  java.nio.channels.Selector;
import  java.nio.channels.ServerSocketChannel;
import  java.util.Iterator;
import  java.util.Set;
import  java.nio.channels.SocketChannel;
 
public  class  NIOServer {
     /*标志数字*/
     private static int flag = 0;
     /*定义缓冲区大小*/
     private static int block = 4096;
     /*接收缓冲区*/
     private static ByteBuffer receiveBuffer = ByteBuffer.allocate(block);
     /*发送缓冲区*/
     private static ByteBuffer sendBuffer = ByteBuffer.allocate(block);
     /*定义Selector*/
     private  Selector selector;
     
     public  NIOServer( int  port)  throws  IOException{
         //打开服务器套接字通道
         ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
         //服务器配置为非阻塞
         serverSocketChannel.configureBlocking( false );
         //检索与此服务器套接字通道关联的套接字
         ServerSocket serverSocket = serverSocketChannel.socket();
         //进行服务的绑定
         serverSocket.bind( new  InetSocketAddress(port));
         //经过open()方法找到Selector
         selector = Selector.open();
         //注册到selector
         serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
         System.out.println( "Server Start -----8888:" );
     }
     //监听
     public  void  listen()  throws  IOException{
         while ( true ){
             //监控全部注册的 channel ,当其中有注册的 IO 操做能够进行时,该函数返回,并将对应的 SelectionKey 加入 selected-key set
             selector.select();
             //Selected-key set 表明了全部经过 select() 方法监测到能够进行 IO 操做的 channel ,这个集合能够经过 selectedKeys() 拿到
             Set<SelectionKey> selectionKeys = selector.selectedKeys();
             Iterator<SelectionKey> iterator = selectionKeys.iterator();
             while (iterator.hasNext()){
                 SelectionKey selectionKey = iterator.next();
                 handleKey(selectionKey);
                 iterator.remove();
             }
         }
         
     }
     //处理请求
     public  void  handleKey(SelectionKey selectionKey)  throws  IOException{
         //接受请求
         ServerSocketChannel serverSocketChannel =  null ;
         SocketChannel socketChannel =  null ;
         String receiveText;
         String sendText;
         int  count;
         //测试此键的通道是否准备好接受新的套接字链接
         if (selectionKey.isAcceptable()){
             //返回建立此键的通道
             serverSocketChannel = (ServerSocketChannel)selectionKey.channel();
             //接受客户端创建链接的请求,并返回 SocketChannel 对象
             socketChannel = serverSocketChannel.accept();
             //配置为非阻塞
             socketChannel.configureBlocking( false );
             //注册到selector
             socketChannel.register(selector, SelectionKey.OP_READ);
         } else  if (selectionKey.isReadable()){
             //返回为之建立此键的通道
             socketChannel = (SocketChannel)selectionKey.channel();
             //将缓冲区清空,以备下次读取
             receiveBuffer.clear();
             //将发送来的数据读取到缓冲区
             
             count = socketChannel.read(receiveBuffer);
         
             
             if (count> 0 ){
                 receiveText =  new  String(receiveBuffer.array(), 0 ,count);
                 System.out.println( "服务器端接受到的数据---" +receiveText);
                 socketChannel.register(selector, SelectionKey.OP_WRITE);
             }
         } else  if  (selectionKey.isWritable()) {  
             //将缓冲区清空以备下次写入  
             sendBuffer.clear();  
             // 返回为之建立此键的通道。  
             socketChannel = (SocketChannel) selectionKey.channel();  
             sendText= "message from server--"  + flag++;  
             //向缓冲区中输入数据  
             sendBuffer.put(sendText.getBytes());  
              //将缓冲区各标志复位,由于向里面put了数据标志被改变要想从中读取数据发向服务器,就要复位  
             sendBuffer.flip();  
             //输出到通道  
             socketChannel.write(sendBuffer);  
             System.out.println( "服务器端向客户端发送数据--:" +sendText);  
             socketChannel.register(selector, SelectionKey.OP_READ);  
         }  
         
     }
     public  static  void  main(String[] args)  throws  IOException {
         int  port =  8888
         NIOServer server =  new  NIOServer(port);
         server.listen();
     }
 
}