Study this matter, don’t care if someone urges you, the most important thing is that you have no consciousness and perseverance.
During review, I will record the process of self-study in the form of notes. The update is expected to be completed before the end of January, please pay attention.
Some pictures of this article come from video notes!! Not my own drawing!!
Netty self – learning (I) – BIO, NIO, AIO brief introduction
Netty self-learning (2) — First introduction to NIO and Buffer
Netty’s self-learning (3) – NIO’s channel
Netty self-learning (4) — Selector for NIO
Netty self – learning (5) – zero copy of NIO
Self – learning of NetTY (6) – Reactor model and introduction of NetTY model
NIO Selector basic introduction
-
Java NIO, with non-blocking IO. You can have one thread, handle multiple client connections, and use a Selector.
-
The Selector can detect if an event has occurred on multiple registered channels (note that multiple channels can be registered to the same Selector as an event), and if an event has occurred, it retrieves the event and handles each event accordingly. This allows you to manage multiple channels with a single thread, that is, multiple connections and requests.
- Reading and writing occurs only when a connection/channel actually has a read or write event, greatly reducing the overhead and eliminating the need to create a thread for each connection and maintain multiple threads
- Avoids the overhead of context switching between multiple threads
Selector API
public abstract class Selector implements Closeable { public static Selector open(); Public int select(long timeout); Public Set< ectionKey> selectedKeys(); public Set< ectionKey> selectedKeys(); // Get all selectionkeys from the inner set}Copy the code
ServerSocketChannel in NIO functions like ServerSocket, SocketChannel functions like Socket selector. Select ()// block selector. Select (1000); // block for 1000 milliseconds and return selector. Wakeup () after 1000 milliseconds; // Wake up selector selectNow(); // Do not block, return immediatelyCopy the code
API for SelectionKey
public abstract class SelectionKey { public abstract Selector selector(); Public abstract SelectableChannel Channel (); Public final Object Attachment (); Public abstract SelectionKey interestOps(int ops); Public final Boolean isAcceptable(); Public final Boolean isReadable(); Public final Boolean isWritable(); }! [](https://p1-jj.byteimg.com/tos-cn-i-t2oaga2asx/gold-user-assets/2020/1/4/16f6~tplv-t2oaga2asx-image.imagefc27f193659b? w=605&h=221&f=png&s=33345)Copy the code
NIO non – blocking network programming principle analysis diagram
-
When a client connects, it gets a SocketChannel through ServerSocketChannel
-
Selector listens for the select method and returns the number of channels on which an event occurred.
-
Register socketchannels with a Selector, a register(Selector sel, int OPS). You can register multiple Socketchannels with a Selector
-
And then it returns a SelectionKey, and it associates that Selector with that Selector, and then it gets each SelectionKey.
-
The SocketChannel is reversely obtained through SelectionKey. The method channel() can be used to complete service processing through the obtained channel
The DEMO presentation
package netty.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.*; import java.util.Iterator; import java.util.Set; Public class NIOServer {public static void main(String[] args) throws Exception{// Create ServerSocketChannel -> ServerSocket ServerSocketChannel serverSocketChannel = ServerSocketChannel.open(); // Get a Selecor object Selector Selector = Selector. Open (); / / bind a port 6666, on the server side to monitor serverSocketChannel. The socket (), bind (new InetSocketAddress (6666)); / / set to non-blocking serverSocketChannel. ConfigureBlocking (false); / / the serverSocketChannel registered to the selector for OP_ACCEPT event serverSocketChannel. Register (selector, SelectionKey. OP_ACCEPT); System.out.println(Selectionkeys =+ selector.keys().size()); // 1 // loop waiting for the client to connectwhile (true) {// Here we wait 1 second, if no event occurs, returnif(selector. Select (1000) == 0) {// No event occurred system.out.println ("Server waited 1 second, no connection");
continue; } // If >0 is returned, the related selectionKey set //1 is retrieved. If >0 is returned, Selector. SelectedKeys () returns a Set of selected events. SelectionKeys = selector.selectedKeys(); System.out.println("SelectionKeys ="+ selectionKeys.size()); Iterator<SelectionKey> keyIterator = selectionkeys.iterator (); Iterator<SelectionKey> keyIterator = selectionkeys.iterator ();while(keyiterator.hasnext ()) {// Get SelectionKey () key = keyiterator.next (); // Handle the events on the channel corresponding to the keyif(key.isacceptable ()) {// if OP_ACCEPT isAcceptable, There is a new client connection / / that the client generates a SocketChannel SocketChannel SocketChannel = serverSocketChannel. The accept (); System.out.println("Client connection successfully generated a socketChannel"+ socketChannel.hashCode()); / / sets the SocketChannel to non-blocking SocketChannel. ConfigureBlocking (false); // Register socketChannel with selector, focusing on event OP_READ, Register (selector, selectionkey. OP_READ, bytebuffer.allocate (1024)); System.out.println("Number of selectionkeys registered after client connection ="+ selector.keys().size()); / / 2 and 4.. }ifSocketChannel channel = (SocketChannel)key.channel(); ByteBuffer = (ByteBuffer)key.attachment(); channel.read(buffer); System.out.println("Form client"+ new String(buffer.array())); } // Manually move the current selectionKey from the collection to avoid repeating keyiterator.remove (); }}}}Copy the code
package netty.nio; import java.net.InetSocketAddress; import java.nio.ByteBuffer; import java.nio.channels.SocketChannel; Public class NIOClient {public static void main(String[] args) throws Exception{// Get a network channel SocketChannel = SocketChannel.open(); / / set non-blocking socketChannel. ConfigureBlocking (false); InetSocketAddress = new InetSocketAddress("127.0.0.1", 6666); // Connect to the serverif(! socketChannel.connect(inetSocketAddress)) {while(! socketChannel.finishConnect()) { System.out.println("Because the connection takes time, the client doesn't block and can do other work..."); }} / /... If the connection is successful, the data String STR = is sent"Hello, Silicon Valley.";
//Wraps a byte array into a buffer
ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
//发送数据,将 buffer 数据写入 channel
socketChannel.write(buffer);
System.in.read();
}
}
Copy the code
SocketChannel and ServerSocketChannel
SocketChannel
Network I/O channel, responsible for read and write operations. NIO writes buffer data to channels, or reads data from channels to buffers.
public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel{ public static SocketChannel open(); Public final SelectableChannel configureBlocking(Boolean block); // Sets blocking or non-blocking modefalsePublic Boolean connect(SocketAddress remote); Public Boolean finishConnect(); Public int write(ByteBuffer SRC); public int write(ByteBuffer SRC); // Write data to the channel public intread(ByteBuffer dst); Public final SelectionKey register(Selector sel, int ops, Object att); Public final void close(); public final void close(); // Close the channel}Copy the code
ServerSocketChannel Listens for new client Socket connections on the server side
public abstract class ServerSocketChannel extends AbstractSelectableChannel implements NetworkChannel{ public static ServerSocketChannel Open (), which gets a ServerSocketChannel Public Final ServerSocketChannelbind(SocketAddress local), set the server port number public final SelectableChannel configureBlocking(Boolean block), set blocking or non-blocking modefalsePublic Final SelectionKey Register (Selector sel, int OPS), SocketChannel Accept (), SocketChannel Accept (), SocketChannel Accept (), SocketChannel Accept (), SocketChannel Accept () Register a selector and set up a listening event}Copy the code
Discuss with each other and make progress together
Please point out any mistakes in your notes.
Persevere!