What is NIO?
New IO, which started in Java 1.4, provides a new non-blocking Java IO operation API.
Non-Blocking IO
Instead of the old version of Blocking IO, it is mostly used for network-related API s.
Why use NIO?
After using NIO, the performance of WEB network program can be further improved.
Simulate Tomcat 7, block IO to process Http requests:
public class BIOHttpServer {
public static void main(String[] args) throws IOException {
ServerSocket socket = new ServerSocket(8080);
System. out. println (Thread. current Thread (). getName ()+ "Start:" +8080);
while(true){
Socket accept = socket.accept();
InputStream inputStream = accept.getInputStream();
byte[] b = new byte[1024];
inputStream.read(b);
System.out.println(new String(b));
// The http response header must write as follows: String response = "HTTP/1.1 200 ok\r\nContent-Length: 11\r\n\r\nHello World\r\n"; accept.getOutputStream().write(response.getBytes()); accept.getOutputStream().flush(); accept.close(); } }
}
NIO's core principles of high performance:
Initiate connection
Operating system receiving connection
TCP Module+Multiplexing Mechanism
A Java thread is selectively processed through the Selector tool
Delivery thread pool with data transfer
Ultimately, threads make the most of it
Using NIO:
Simulate Tomcat 8.5, NIO processes Http requests:
public class NIOHttpServer {
public static void main(String[] args) throws IOException {
// 1. Server Socket Channel Binding Port ServerSocketChannel socket = ServerSocketChannel.open(); socket.configureBlocking(false); // no-Blocking socket.bind(new InetSocketAddress(8080)); System.out.println("NIO Server startup, port:"+8080); // 2. Getting new connections // selector gets different tcp connection dynamics under different operating systems Selector selector = Selector.open(); // Selector, queries TCP connections according to conditions socket.register(selector, SelectionKey.OP_ACCEPT); while(true){ selector.select(1000); //If there is no new connection, wait // 3. Processing query results Set<SelectionKey> keys = selector.selectedKeys(); Iterator<SelectionKey> iterator = keys.iterator(); while(iterator.hasNext()){ SelectionKey result = iterator.next(); //Processing according to different types if(result.isAcceptable()){ //3.1 Get the new connection object // nio implies that accept is not blocked and returns null without connection SocketChannel accept = socket.accept(); if(accept!=null){ // Register Connection Objects for Attention accept.configureBlocking(false);// no-Blocking accept.register(selector, SelectionKey.OP_READ); } } if(result.isReadable()){ //3.2 Connections with Data Requests SocketChannel channel = (SocketChannel) result.channel(); // In the process of processing, cancel the registration of selector corresponding connection to avoid duplication result.cancel(); // NIO Reading and Writing: Byte Buffer ByteBuffer byteBuffer = ByteBuffer.allocate(1024); channel.read(byteBuffer); byteBuffer.flip(); //Mode transformation byte[] b = byteBuffer.array(); String request = new String(b); //Processing requests... System.out.println(request); //Data Response: NIO Write Data String response = "HTTP/1.1 200 ok\r\nContent-Length: 11\r\n\r\nHello World\r\n"; channel.write(ByteBuffer.wrap(response.getBytes())); // Processing completed, re-registered, continue to receive and process new connections // channel.register(selector, SelectionKey.OP_READ); } // Delete processed results (events) iterator.remove(); } // Check that the process is in place to clear the previous call effect selector.selectNow(); } }
}
(This article was originally created by the technology teacher of the source code era. Please indicate the source for reprinting!)