nio (1) Basic Introduction

Disclaimer: This article is a blogger original article, follow the CC 4.0 BY-SA copyright agreement, reproduced, please attach the original source link and this statement.
This link: https://blog.csdn.net/m0_38060977/article/details/102754441

NIO introduce a

nio and the difference io:
1.NIO is block-oriented, IO stream oriented. Means for streaming the stream from each read one or more bytes, until all bytes are read, they are not cached anywhere. And for the first data block will read a transfer zone, can be moved back and forth so NIO read data, more flexible and convenient.
2.IO is blocked, NIO can not be blocked (network programming). Fewer system resources.

Two Channel

Channel is two-way, both can be used for read operations, but also can be used to write.
NIO The main achievement Channel are:
FileChannel
DatagramChannel
SocketChannel
ServerSocketChannel
here to see the name can be seen: Corresponding file IO, UDP and TCP (Server and Client)

The most basic example FileChannel

RandomAccessFile aFile = new RandomAccessFile("data/nio-data.txt", "rw");
    FileChannel inChannel = aFile.getChannel();

    ByteBuffer buf = ByteBuffer.allocate(48);

    int bytesRead = inChannel.read(buf);
    while (bytesRead != -1) {

      System.out.println("Read " + bytesRead);
      buf.flip();

      while(buf.hasRemaining()){
          System.out.print((char) buf.get());
      }

      buf.clear();
      bytesRead = inChannel.read(buf);
    }
    aFile.close();

SocketChannel
non-blocking characteristics of the power comes from the Channel NIO part of
some operation on a socket could block indefinitely. For example, a call to accept () method are likely to be waiting for a client to connect to clog; call read () method may be blocked because there is no data to read, until the other end of the connection coming from the new data. In summary, creating / receiving data connection or read and write I / O calls, could indefinitely blocks until the underlying network to realize what happened. Slow, lossy network, or just a simple network failure may result in a delay at any time. Unfortunately, before calling a method you can not know whether it is blocked. NIO the channel is an important feature abstraction can configure its blocking behavior, in order to achieve non-blocking channel.
Call a method in a non-blocking channels will always return immediately . This call return value indicates the degree of completion of the requested operation. For example, the call accept () method on a ServerSocketChannel a non-blocking, if the connection request, the client SocketChannel returns, else return null

三 Buffer

Buffer is actually a container, a continuous array. Channel provides read data from files, network channels, but reading and writing of data to go through Buffer (Channel use must fit Buffer).

Achieve
ByteBuffer, CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, ShortBuffer, respectively corresponding to the basic data types: byte, char, double, float , int, long, short. Of course NIO there MappedByteBuffer, HeapByteBuffer, DirectByteBuffer and so on
to write data to the Buffer:

Use
1. write data to the Buffer:
from Channel wrote Buffer (fileChannel.read (buf)) channel to read the data, make sure both read data written to the buffer
put through the Buffer () method (buf. PUT (...))
2. read the data from Buffer:
reads from Buffer to Channel (channel.write (buf))
using the get () method of reading data (buf.get from Buffer, ())

Common properties

name a Remarks
position Next to operate (read or write) the elements of the subscript
capacity The total length of the array of buffers
limit The first can not read or write element subscript
mark For recording the position of the current position of a front or a default -1

Common methods
1.flip (): position set back to 0, and the limit value is set to the position before
2.clear (): position is set back to 0, provided Capacity limit, in other words, Buffer is cleared, in fact, the data Buffer has not been clear, but these markers can tell us where to start to write data to Buffer.
3.compact (): read the copy all but the beginning of the data to the Buffer. The position is then set to the last element directly behind unread. limit property is still as clear () method, as set to capacity. Buffer is now ready to write data, but does not overwrite data unread.
4.mark (): you can mark a specific position Buffer in, after which the method can be restored to this position by calling Buffer.reset ().
5.rewind (): The position set back to zero, so you can re-read all the data in the Buffer. limit remains unchanged, indicates how many elements can be read from the Buffer. (Re-read)

四 Selector

Selector to run single-threaded to handle multiple Channel, if your application opens multiple channels, each connected to the flow are low, use Selector comes in handy.
For example, in a chat server. To use the Selector, have to register Channel Selector, then call it a select () method. This method blocks until the channel has a registered event ready. Once this method returns, the thread can handle these events, like the example of an event of a new incoming connections, the data reception and the like.

In technical terms, the selector is a multiplexer, a selector as a plurality of channels capable of managing I / O operations. However, if the traditional way to deal with so many clients, the methods used are cyclically one by one to check whether all the client has I / O operations, if there are current client I / O operations, customers may be able to present end throw a thread pool to handle, if there is no I / O operation at a polling is carried out when all clients are polling and then start from scratch after polling ; this approach is also very very stupid and a waste of resources because most of the clients are not I / O operations, we are also going to inspect; and Selector is not the case, it can manage multiple I / O at the same time inside when there is a channel I / O operations, he will notify Selector, Selector is to remember this channel has I / O operations, and know what kind of I / O operations, is to read it? It is to write it? Or accept new connections; so if you use Selector, the results it returns only two results, one is 0, that does not need any client I / O operations at the time of your call, the other result is a set I need client / O operations, then you do not need to re-examine, because it is returned to you is definitely what you want. In such a way notification is much more efficient than the kind of proactive polling of the way !

Selector ## to the register
for use with the Channel Selector and must be registered to the Channel Selector, achieved by SelectableChannel.register () method,

            ssc= ServerSocketChannel.open();
            ssc.socket().bind(new InetSocketAddress(PORT));
            ssc.configureBlocking(false);
            ssc.register(selector, SelectionKey.OP_ACCEPT);

Note that register () method of the second parameter. This is an "interest collection," meaning by Selector interested in what events while monitoring Channel. You can monitor four different types of events:

  1. Connect
  2. Accept
  3. Read
  4. Write
    these four events with four constants SelectionKey be represented:
  5. SelectionKey.OP_CONNECT
  6. SelectionKey.OP_ACCEPT
  7. SelectionKey.OP_READ
  8. SelectionKey.OP_WRITE

SelectionKey

When registering the Channel Selector, register () method returns a SelectionKey object. This object contains a number of properties you are interested in:
1.interest collection of
interest set: the Selector registered as a channel as described, interest is a collection of your choice set of events of interest. Reading and writing can be set by SelectionKey interest.

2.ready collection of
ready collection is a collection operation channel is already ready. After a selection (Selection), you will first visit the ready set. Selection will be explained in the next section. Such access may be ready collections:

int readySet = selectionKey.readyOps();
//可以用像检测interest集合那样的方法,来检测channel中什么事件或操作已经就绪。但是,也可以使用以下四个方法,它们都会返回一个布尔类型:
selectionKey.isAcceptable();
selectionKey.isConnectable();
selectionKey.isReadable();
selectionKey.isWritable();

3.Channel

//从SelectionKey访问Channel和Selector很简单。如下:
Channel  channel  = selectionKey.channel();
Selector selector = selectionKey.selector();

4.Selector additional objects (optional)
Each time a register returns corresponding objects SelectionKey

//可以将一个对象或者更多信息附着到SelectionKey上,这样就能方便的识别某个给定的通道。例如,可以附加 与通道一起使用的Buffer,或是包含聚集数据的某个对象。使用方法如下:
selectionKey.attach(theObject);
Object attachedObj = selectionKey.attachment();
//还可以在用register()方法向Selector注册Channel的时候附加对象。如:
SelectionKey key = channel.register(selector, SelectionKey.OP_READ, theObject);

select()

Overloaded select () method
below is select () method:
int select ()
int the SELECT (Long timeout)
int selectNow ()
select () blocks until at least one channel is ready in the event you register.
select (long timeout) and select (), except that will clog up timeout milliseconds (parameter).
selectNow () does not block, no matter what channel-ready returns immediately (Translator's Note: This method performs non-blocking operation if the selected operation since a choice before, did not become an alternative channel, this method returns null .).

Once called select () method, and the return value indicates that one or more channels is ready, and then "the selected key set (selected key set)" by calling the ready passage of the selectedKeys selector () method to access. As follows:

Set selectedKeys = selector.selectedKeys();

1. Note that at the end of each iteration keyIterator.remove () call. Selector will not remove yourself from SelectionKey instance selected-key set. It must be removed when finished with their own channel. The next time the channel becomes ready, Selector will again be placed in selected-key set.
2. After traversing or integrated set, performs the collection clear () method.

reference

1. break JAVA NIO technical barriers
2. http://wiki.jikexueyuan.com/project/java-nio-zh/java-nio-channel.html

Guess you like

Origin blog.csdn.net/m0_38060977/article/details/102754441