java NIO 第一弹----概览
摘要:
Non-blocking I/O (usually called NIO, and sometimes called "New I/O") is a collection of Java programming language APIs that offer features for intensive I/Ooperations. It was introduced with the J2SE 1.4 release of Java by Sun Microsystems to complement an existing standard I/O. NIO was developed under the Java Community Process as JSR 51.[1]
大意:非阻塞I/O(通常叫做NIO,有时也叫新的I/O),是一组提供了加强版I/O操作特性的java api。在java1.4时由sun公司引入。
本系列主要着眼于网络部分,对本地文件操作没有涉及。接下来先看一段代码,展示了最简单Echo服务端。
代码示例
1 ByteBuffer bb = ByteBuffer.allocate(1024); 2 /**创建选择器*/ 3 Selector selector = Selector.open(); 4 /**打开一个服务端通道*/ 5 ServerSocketChannel ssc = ServerSocketChannel.open(); 6 /**设置为非阻塞*/ 7 ssc.configureBlocking(false); 8 /**从通道中拿到服务端socket*/ 9 ServerSocket ss = ssc.socket(); 10 /**绑定一个端口*/ 11 InetSocketAddress addr = new InetSocketAddress(1234); 12 ss.bind(addr); 13 /**注册感兴趣事件,服务端通道只能注册接受事件*/ 14 ssc.register(selector, SelectionKey.OP_ACCEPT); 15 String receivedMsg = ""; 16 /**主循环*/ 17 while(true){ 18 int num = selector.select(); 19 System.out.println(num+"个事件发生。。。"); 20 Set<SelectionKey> selectedKeys = selector.selectedKeys(); 21 Iterator<SelectionKey> it = selectedKeys.iterator(); 22 23 /**循环处理每个通道事件*/ 24 while(it.hasNext()){ 25 SelectionKey key = it.next(); 26 it.remove(); 27 if(key.readyOps() == SelectionKey.OP_ACCEPT){ 28 System.out.println("新连接建立事件"); 29 ServerSocketChannel serverSocketChannel = (ServerSocketChannel) key.channel(); 30 SocketChannel sc = serverSocketChannel.accept(); 31 sc.configureBlocking(false); 32 sc.register(selector, SelectionKey.OP_READ); 33 }else if((key.readyOps()&SelectionKey.OP_READ) == SelectionKey.OP_READ){ 34 System.out.println("读事件"); 35 SocketChannel sc = (SocketChannel) key.channel(); 36 sc.read(bb); 37 receivedMsg = new String(bb.array(),0,bb.position()); 38 bb.clear(); 39 sc.register(selector, SelectionKey.OP_WRITE); 40 }else if(key.readyOps() == SelectionKey.OP_WRITE){ 41 System.out.println("写数据"); 42 SocketChannel sc = (SocketChannel) key.channel(); 43 sc.write(ByteBuffer.wrap(receivedMsg.getBytes())); 44 /**没有cancel就会一直循环进入此处,因为只要通道不阻塞会一直有写事件,所以使用完需要取消*/ 45 key.cancel(); 46 }else{ 47 System.out.println("other event"); 48 } 49 } 50 }
此处代码是一个将收到的信息发回去的服务端代码,给出了使用nio写服务端的一般流程。
此处可以先有个概念和总体认识,接下来会对涉及到的重要的类进行介绍,欢迎批评指正,大家讨论进步。
注:本例没有处理IOException,实际代码要处理,不然一个客户端强行关闭socket就会使服务端挂掉。
java nio 第一弹
时间: 2024-10-14 19:26:16