What is NIO? The thread can do something else when it is processing data, if it is still reading data from the channel to the buffer, and then comes back to process the data
What is a channel?
A channel represents a connection to an entity. Entities include files, network sockets, and other devices that can perform I/O operations (read and write). The concept of analog flow. The difference with flow is that
-
A channel is readable and writable, but a stream either writes or reads
-
Chanel can read and write asynchronously
-
Data is always read from a channel to buffer or written from buffer to a channel
Reading or writing to a stream is usually a one-time operation. Data is not cached during reading, which means there is no way to move the data to the desired location. Caching is the only way to achieve this function
What are channels in Java?
- FileChannel: The channel of the connection file, obtained through the getChannel method of the file object
The FileChannel write() method does not guarantee that a number of bytes will be written to the channel at one time; In addition, it cannot be set to non-blocking, only blocking mode can always be set
-
DatagramChannel: Handles UDP connections through datagramchannel.open () and then binds the socket to the port
-
SocketChannel: An established TCP network socket that handles TCP connections. Socketchannel.open () calls its own connet
-
ServerSocketChannel: Listens for TCP connections to be established. This can be done with serverSocketChannel.open (), then binds the port to be listened on and waits for the connection to arrive. Each established connection returns a SocketChannel
In non-blocking mode, the accept method that waits for a connection will return immediately. In addition, multiple connections may be established, so listeners are usually placed in a while loop
What is a Buffer?
A wrapper class that facilitates manipulation of data in a block of memory. It has three properties
-
Capacity: Indicates the capacity of the Buffer. If the Buffer is full, data cannot be written
-
Position: Start position of read or write
-
Limit: Indicates the amount of data that can be written to the buffer in write mode. The maximum value is capacity. Read mode indicates the amount of data that can be retrieved from the buffer
Switching from write mode to read mode is done with flip(). After the call, limit is set to position and positon is set to 0.
The clear or Compact method is called after the data is read and converted to write. Clear sets position to 0 and limit to Capacity. Compact copies the original data to the starting position. Then set the following position to position and limit to Capacity
Use of mark and reset: During reading, mark is in the current position. After reading, reset is back to the position before reading
How to read data into multiple buffers?
Create an array to hold data to write, or data to read, and then read or write, but this method is not suitable for reading variable-length messages
Buffer[] bArr = {head,body}; channel.read(bArr); Buffer[] wArr={head,body} channel.write(wArr); / / writeCopy the code
What is multiplexing?
In networks, multiplexing is the process of combining multiple analog or digital signals into a single signal that can be transmitted over a shared medium. The goal is to share scarce resources, such as the fact that historically multiple landline telephone signals were made over a single wire.
A multiplexed signal is transmitted through a communication channel such as a cable. The multiplexer divides the capacity of the communication channel into several logical channels, each channel corresponding to the signal or data stream to be transmitted, and the receiver extracts the corresponding original signal through demultiplexing
Images and content from Wikipedia
What does Selector do?
Events used to monitor multiple channels, such as channel connection establishment, data arrival, and so on.
Selector is a multiplexer of SelectableChannel. There are different implementations for different operating systems, such as PollSelectorImpl and EpollSelector. Of course, you can also customize the implementation.
The SelectionKey is used to indicate that a SelectableChannel is registered with a Selector, and inside the Selector a collection of three selection keys is maintained
-
A key set represents a registered channel that uses this Selector, returned by keys()
-
SelectedKeys (); selectedKeys(); selectedKeys(); selectedKeys(
-
Cancelled -key set represents a channel that has performed cancel but has not yet completed the untying process, and is not available directly
When you create a new Selector, all three of these sets are empty
You can actually manage all channels with a single thread
Selector Use examples
// create selector selector selector = selector. Open (); // To use Selector must be set tofalse, at the same time means FileChannel is can't use the Selector channel. ConfigureBlocking (false); // SelectionKey has 4 values, representing 4 events: connect, Accept,read// The interestOps method can get the events that are of interest to the channel at the time of registration. InterestSet & selectionkey. OP_ACCEPT the result is ACCEPT or not // Registered in this way, indicating that the current channel needs to listen onreadEvent, if interested in more than one event, then you can use SelectionKey. OP_READ | SelectionKey. OP_WRITE way / / registration method can also add another parameter, SelectionKey key = channel.register(selector, selectionkey.op_read);while(true) {//select () from channel if none of the registered events are good, then block, return value to indicate the number of chanel events that have occurred; Int readyChannels = selector. Select (); //selectNow () does not block, and returns 0 if it is not ready.if(readyChannels == 0) continue; SelectedKeys = selector. SelectedKeys (); Iterator<SelectionKey> keyIterator = selectedKeys.iterator();while(keyIterator.hasNext()) {
SelectionKey key = keyIterator.next();
if(key.isacceptable ()) {//SeverSocketChannel accepts a new connection}else if(key.isConnectable()) {// A connection has been established with the remote}else if(key.isreadable ()) {//channel readable}else if(key.iswritable ()) {//channel writable} // Keyiterator.remove () must be executed manually; }}Copy the code
Wakeup: Returns immediately if the channel is currently blocked in select
The attached
Java NIO reference