This article is a notebook written by Java 7 a month ago. I think it is very important to add it to my blog. A lot of nonsense, Chinese technical books are harmful. When I read this part of the book, I did not make it clear. Finally, I checked the API documentation and wrote my own Demo for a night and basically understood it, I have added a lot of my understanding in the notes. It's just an original one.
One socket Channel
1. Blocked socket Channel
Corresponding to Socket and ServerSocket, NIO provides etchannel and ServerSocketChannel. These two channels support both general blocking mode and more efficient non-blocking mode.
The client uses SocketChannel. open () method to open a Socket channel. If the SocketAddress parameter is provided at this time, the connection starts automatically. Otherwise, you need to call the connect () method to connect automatically. After the connection is created, it can be read and written using Buffer like a normal Channel, which is in blocking mode.
The server is created through ServerSocketChannel. open () and bound to a listening address using the bind () method. Finally, the accept () method is called to block waiting for client connection. After the client is connected, A SocketChannel is returned for read/write interaction with the client.
In general, the blocking mode is a flip of the net Package I/O, only implemented using Channel and Buffer.
2. multiplexing socket channel (non-blocking IO implemented by Selector)
The idea of socket channel multiplexing is to create a Selector and register multiple channels. When a socket has an event of interest, you can select this channel for operations.
The server code is as follows, and the instructions are included in the Notes:
01
// Create a selector that can be closed with close (). isOpen () indicates whether the selector is in the open state and does not belong to the current thread.
02
Selector selector = Selector. open ();
03
// Create a ServerSocketChannel and bind it to the specified port
04
ServerSocketChannel server = ServerSocketChannel. open ();
05
Server. bind (new InetSocketAddress ("127.0.0.1", 7777 ));
06
// It is very important to set the non-blocking mode.
07
Server. configureBlocking (false );
08
// Register the accept event of the server socket channel in the selector
09
// ServerSocketChannel is only available for OP_ACCEPT, OP_CONNECT, OP_READ, and OP_WRITE for SocketChannel
10
Server. register (selector, SelectionKey. OP_ACCEPT );
11
While (true ){
12
// Test the wait event, which is divided into directly returned selectNow () and blocked wait select (). You can also add a parameter to indicate blocking timeout.
13
// There are two methods to stop blocking: the disconnection process and selector. wakeup (). When an event occurs, the system will automatically wake up ()
14
// The number of select events returned by the method (see the notes below to explain why this value may be 0 ).
15
// When selector is blocked by select (), other threads call the register of the same selector and it will be blocked until the select returns
16
// The select Operation adds the Key of the event of interest to selectionKeys (add or subtract)
17
If (selector. select () = 0 ){//
18
Continue;
19
}
20
21
// Obtain the Key set with the time of interest. Each SelectionKey corresponds to a registered channel.
22
Set <SelectionKey> keys = selector. selectedKeys ();
23
// One more sentence, selector. keys (), returns all selectionkeys (including those without events)
24
For (SelectionKey key: keys ){
25
// Only ServerSocketChannel can trigger OP_ACCEPT.
26
If (key. isAcceptable ()){
27
// Obtain the socket channel with the client
28
SocketChannel channel = (ServerSocketChannel) key. channel (). accept ();
29
// Also set to non-blocking mode
30
Channel. configureBlocking (false );
31
// It will also be registered on the client channel on the selector. The OP_READ corresponds to a readable event (the other party has written data), and the associated selector can be obtained through the key.
32
Channel. register (key. selector (), SelectionKey. OP_READ, ByteBuffer. allocate (1024 ));
33
}
34
// OP_READ has readable data
35
If (key. isReadable ()){
36
SocketChannel channel = (SocketChannel) key. channel ();
37
// Obtain the attachment, which is the third parameter of the above SocketChannel for register.
38
ByteBuffer buffer = (ByteBuffer) key. attachment ();
39
// Read the data. In fact, it should be read cyclically until the data cannot be read.
40
Channel. read (buffer );
41
// Changes the event of interest, which can be a bit or operated | combination time
42
Key. interestOps (SelectionKey. OP_READ | SelectionKey. OP_WRITE );
43
}
44
// The OP_WRITE write status is usually triggered, so you only pay attention to it when you need a write operation.
45
If (key. isWritable ()){
46
// Write data passes by. You can create a self-built buffer or use an attachment object (depending on the Situation). Pay attention to flip after writing the buffer.
47
//......
48
// After writing, write status should be removed. Otherwise, the write event will be triggered all the time.
49
Key. interestOps (SelectionKey. OP_READ );
50
}
51
52
// Because the select operation only adds selectedKeys, after the key is processed, we need to remove the key from it.
53
Keys. remove (key );
54
}
55
}
Here, we need to focus on what the select Operation has done (according to the symptom, it seems that this document does not exist). He checks the status of each channel corresponding to each Key in the keys, if there is a follow state, it is decided to return, then the Key object will be added to selectedKeys at the same time, and return the number of objects in this change of selectedKeys (the objects originally in selectedKeys are excluded), because a Key corresponds to a channel (may be in multiple States at the same time, so note that none of the above if statements write else), so it is also possible to return 0 for select statements. In addition, the OP_WRITE and OP_CONNET statuses cannot be followed for a long time. You only need to listen when necessary and remove them immediately after processing. If no concern is found, the select statement will be blocked until the status changes or times out.
Other methods of SelectionKey: attach (Object) sets the attachment for the key and returns the previous attachment; interestOps () and readyOps () return the following and current statuses; cancel () isValid () indicates whether the key is valid (when the key is not registered, the channel is closed, and the selector is disabled before these three events occur, the key is valid, but it does not include the other party closing the channel, so read and write should be aware of exceptions ).
Another status is not used. OP_CONNECT is mainly used on the client. The corresponding key method is isConnectable (), indicating that the connection has been created.
The non-blocking implementation client is as follows:
01
Selector selector = Selector. open ();
02
// Create a socket channel. Note that the parameter-free format must be used here.
03
SocketChannel channel = SocketChannel. open ();
04
// Set to non-blocking mode. This method must be called before the actual connection (so the server address cannot be provided during open; otherwise, the server will be automatically connected)
05
Channel. configureBlocking (false );
06
// Connection to the server. Because it is in non-blocking mode, this method will initiate a connection request and directly return false (blocking mode is to wait until the link is successful and return whether it is successful)
07
Channel. connect (new InetSocketAddress ("127.0.0.1", 7777 ));
08
// Register the link status
09
Channel. register (selector, SelectionKey. OP_CONNECT );
10
While (true ){
11
// The prefix is similar to that on the server
12
//...
13
// Obtain the Key set with the time of interest. Each SelectionKey corresponds to a registered channel.
14
Set <SelectionKey> keys = selector. selectedKeys ();
15
For (SelectionKey key: keys ){
16
// In the case of OP_CONNECT, the method returns true if the link is successful or fails.
17
If (key. isConnectable ()){
18
// Due to non-blocking mode, connect only initiates a connection request. The finishConnect () method will block the connection until the link ends and return whether the connection is successful.
19
// Another isConnectionPending () returns whether it is in the connection status (still in three handshakes)
20
If (channel. finishConnect ()){
21
// If the link is successful, you can perform some processing on your own.
22
//...
23
// After processing, you must remove OP_CONNECT and follow OP_READ.
24
Key. interestOps (SelectionKey. OP_READ );
25
}
26
}
27
// The suffix is slightly similar to that on the server
28
//...
29
}
30
}
Although this is the case, the server and client can choose whether to adopt the non-blocking mode on their own. The client in the blocking mode is OK to connect to the server in the non-blocking mode.
Asynchronous IO channel of NIO2
The following APIs are provided by Java 7. The old version is unavailable.
There are two implementation methods for asynchronous IO channels. One is the original method in the blocking mode (mainly refers to read and write. For details, refer to the API documentation) uploaded to a CompletionHandler instance for callback. In addition, it can be used to return a Future instance (java 5 is a new synchronization toolkit. util. concurrent API), and then use the get method to obtain the returned results as appropriate. The asynchronous file I/O channel is AsynchronousFileChannel, And the asynchronous socket channel is AsynchronousServerSocketChannel, which corresponds to their respective original channels.
Asynchronous I/O needs to be associated with an AsynchronousChannelGroup object, which is essentially a thread pool for I/O. AsynchronousChannelGroup objects can be created using withThreadPool () and withCachedThreadPool () in their own static methods. withFixedThreadPool () provides a thread pool (the thread pool is also java, a newly added synchronization toolkit for java 5. util. concurrent API ). When an asynchronous channel creates an open (), this object can be passed in for association. If this object is not provided, the system group is used by default. However, it should be noted that the thread pool of the system group is a daemon thread pool, and the JVM may end normally before the read/write is completed. AsynchronousChannelGroup requires shutdowm () after use, which is similar to the shutdown of the thread pool.
Author: Dead Water fox