The static forName (String encode) method of the Charset class returns a Charset object, which represents the encoding type specified by the encode parameter. For example, the following code creates a Charset object representing the "GBK" encoding:
Charset charset = Charset. forName ("GBK ");
The Charset class also has a static method defaultCharset (), which returns the Charset object representing the default character encoding of the local platform.
Channel is used to connect the buffer to the data source or data sink (Data destination). 4-8 shows that the data of the data source reaches the buffer through the pipeline, and the data in the buffer reaches the data sink through the Channel.
4-9 shows the main layer of the Channel.
Java. nio. channels. Channel interface only declares two methods.
Close (): closes the channel; isOpen (): determines whether the channel is open.
The channel is opened when it is created. Once the channel is closed, it cannot be opened again.
The two most important sub-interfaces of the Channel interface are ReadableByteChannel and WritableByteChannel. the ReadableByteChannel interface declares the read (ByteBuffer dst) method. This method reads data from the data source into the ByteBuffer buffer specified by the parameter. The WritableByteChannel interface declares the write (ByteBuffer src) method, this method writes the data in the ByteBuffer buffer specified by the parameter to the data sink. 4-10 shows the relationship between the Channel and Buffer. the ByteChannel interface is a convenient interface that extends the ReadByteChannel and WritableByteChannel interfaces, and supports both read and write operations.
Figure 4-10 Relationship between Channel and Buffer
The ScatteringByteChannel interface extends the ReadByteChannel interface to allow Scattered Data Reading. distributed Data Reading means that a single read operation can fill multiple buffers. the ScatteringByteChannel interface declares the read (ByteBuffer [] dsts) method. This method fills data read from the data source in ByteBuffer arrays specified by the parameter in sequence. the GatheringByteChannel interface extends the WritableByteChannel interface to allow concentrated Data Writing. centralized data writing means that a single write operation can write data from multiple buffers to a data sink. the GatheringByteChannel interface declares the write (ByteBuffer [] srcs) method. This method writes data in each ByteBuffer array specified by the parameter to the data sink. the speed of input and output operations can be further improved by reading data in a distributed manner and writing data in a centralized manner.
The FileChannel class is the implementation class of the Channel interface, representing a Channel connected to a file. this class implements ByteChannel, ScatteringByteChannel, and GatheringByteChannel interfaces. It supports read operations, write operations, distributed read operations, and concentrated write operations. the FileChannel class does not provide a public constructor. A single client program cannot use the new statement to construct its implementation. however, the getChannel () method is provided in the FileInputStream, FileOutputStream, and RandomAccessFile classes. This method returns the corresponding FileChannel object.
SelectableChannel is also a channel that not only supports blocking I/O operations, but also non-blocking I/O operations. selectableChannel has two subclasses: ServerSocketChannel and SocketChannel. socketChannel also implements the ByteChannel interface, which has the read (ByteBuffer dst) and write (ByteBuffer src) methods.
Note the main hierarchy of the Channel shown in Figure 4-9 above. This is a little different from the original book. The classes in it are jdk1.5. SocketChannel implements the ByteChannel, ScatteringByteChannel, and GatheringByteChannel interfaces, socketChannel also has a subclass of SocketChannelImpl. The source code of SocketChannelImpl cannot be seen.
5. SelectableChannel class
The SelectableChannel class is a channel that supports blocking I/O and non-blocking I/O. in non-blocking mode, read/write data is not blocked, and SelectableChannel can register read-ready and write-ready events with Selector. selector monitors these events. when an event occurs, for example, a read-ready event occurs, SelectableChannel can perform read operations.
The main method of SelectableChannel is as follows:
Public SelecotableChannel configureBlocking (boolean block) throws IOException
When the number block is true, the SelectableChannel is set to the blocking mode. If the block parameter is false, the SelectableChannel is set to the non-blocking mode. by default, SelectableChannel adopts blocking mode. this method returns the reference of the SelectableChannel object, which is equivalent to "return this ".
Public SelectionKey register (Selector sel, int ops) throws ClosedChannelExceptionpublic SelectionKey register (Selector sel, int ops, Object attachment) throws ClosedChannelException
The last two methods both register time with Selector. For example, the following socketChannel (a subclass of SelectableChannel) registers read-ready and write-ready events with Selector:
SelectionKey key = socketChannel. register (selector, SelectionKey. OP_READ | SelectionKey. OP_WRITE );
The register () method returns a SelectionKey object, which is used to track registered events. the second register () method also has an Object-type parameter attachment, which is used to associate the SelectionKey with an attachment. When a registered event occurs and the event needs to be processed, you can obtain this attachment from SelectionKey, which can contain information related to processing this event. the following two codes are equivalent:
MyHandler handler = new MyHandler (); // The object responsible for event processing
SelectionKey key = socketChannel. register (selector, SelectioinKey. OP_READ | SelectionKey. OP_WRITE,Handler);
It is equivalent:
MyHandler handler = new MyHandler (); // The object responsible for event processing
SelectionKey key = socketChannel. register (selector, SelectioinKey. OP_READ | SelectionKey. OP_WRITE );
Key. attach (Handler); // Associate an attachment with SelectionKey
6. ServerSocketChannel class
SeverSocketChannel inherits the configureBlocking () and register () methods from SeletableChannel. serverSocketChannel is a replacement class of ServerSocket and has the accept () method used to receive client connections. serverSocket does not have a public constructor. You must use its static method open () to create a ServerSocketChannel object. each ServerSocketChannel object is associated with a ServerSocket object. the socket () method of ServerSocketChannel returns the ServerSocket object associated with it. you can bind a server process to a local port by using the following methods:
ServerSocketChannel. socket (). bind (port );
The main method of ServerSocketChannel is as follows:
Public static ServerSocketChannel open () throws IOException
This is a static factory method of the ServerSocketChannel class. It returns a ServerSocketChannel object which is not bound to any local port and is in blocking mode.
Public SocketChannel accept () throws IOException
Similar to the accept () method of ServerSocket, it is used to receive client connections. if the ServerSocketChannel is in a non-blocking state, this method returns null immediately when no client connection is available. If the ServerSocketChannel is in a blocking state, it will continue to block when no client connection is available, until a client is connected, or IOException occurs.
It is worth noting that the SocketChannel object returned by this method is in blocking mode. to change it to non-blocking mode, you must execute the following code:
SocketChannel. configureBlocking (false );
Public final int validOps ()
Returns events generated by the ServerSocketChannel. This method always returns SelectionKey. OP_ACCEPT.
Public ServerSocket socket ()
Returns the ServerSocket object associated with the ServerSocketChannel. Each ServerSocketChannel object is associated with a ServerSocket object.
7. SocketChannel class
SocketChannel can be seen as an alternative to Socket, but it has more functions than Socket. socketChannel not only inherits the configureBlocking () and register () methods from the SelectableChannel parent class, but also implements the ByteChannel interface. Therefore, it has the read (ByteBuffer dst) used to read and write data) and write (ByteBuffer src) methods. socketChannel does not have a public constructor. You must use its static method open () to create a SocketChannel object.
The main method of SocketChannel is as follows:
Public static SocketChannel open () throws IOExceptionpublic static SocketChannel open (SocketAddress remote) throws IOException
The static factory method open () of SocketChannel is used to create the SocketChannel object. The second construction method with parameters will also establish a connection with the remote server. in blocking mode and non-blocking mode, the second open () method has different behaviors, which is similar to the connect () method of the SocketChannel class. For more information, see connect () method Introduction.
The following two pieces of code are equivalent:
SocketChannel socketChannel = SocketChannel. open ();
SocketChannel. connect (remote); // remote is of the SocketAddress type.
It is equivalent:
SocketChannel socketChannel = SocketChannel. open (remote); // remote is of the SocketAddress type.
It is worth noting that the SocketChannel object returned by the open () method is in blocking mode. to change it to non-blocking mode, you must execute the following code:
SocketChannel. configureBlock (false );
Public final int validOps ()
Return events generated by SocketChannel. This method always returns the following values:
SelectionKey. OP_CONNECT | SelectionKey. OP_READ | SelectionKey. OP_WRITEN
Public Socket socket ()
Return the Socket object associated with the SocketChannel. Each SocketChannel object is associated with a Socket object.
Public boolean isConnected ()
Determine whether the underlying Socket has established a remote connection.
Public boolean isConnectionPending ()
Determine whether a remote connection is in progress. true is returned when the remote connection operation has started but has not been completed. Otherwise, false is returned. that is to say, when the underlying Socket has not started the connection, or the connection has been successful, this method will return false.
Public boolean connect (SocketAddress remote) throws IOException
Establish a remote connection to the underlying Socket. when the SocketChannel is in non-blocking mode, if the connection succeeds immediately, the method returns true. If the connection fails immediately, the method returns false. The program must call finishConnect () later () method to complete the connection. when the SocketChannel is in blocking mode, if the connection is successful immediately, this method returns true. If the connection cannot be successful immediately, it will be blocked until the connection is successful or an I/O exception occurs.
Public boolean finishConnect () throws IOExcetion
Try to connect to the remote server. in non-blocking mode, establishing a connection starts from calling the connect () method of SocketChannel and ends when the finishConnect () method is called. if the finishConnect () method successfully completes the connection, or the connection has been established before the method is called, The finishConnect () method returns true immediately. if the connection operation is not completed, false is returned immediately. If the connection operation fails due to an exception, an I/O exception is thrown.
In blocking mode, if the connection operation is not completed, it will be blocked until the connection is completed or an I/O exception occurs.
Public int read (ByteBuffer dst) throws IOException
Reads several bytes from the Channel and stores them in the ByteBuffer specified by the parameter. assume that before the read () method is executed, the location of ByteBuffer is p, the remaining capacity is r, and r is equal to dst. the return value of the remaining () method. assuming that the read () method actually reads n Bytes, then 0 ≤ n ≤ r. after the read () method is returned, the location of the ByteBuffer referenced by the dst parameter changes to p + n, and the limit remains unchanged, as shown in 4-11:
Figure 4-11 read () method reads n Bytes
In blocking mode, the read () method will try to read r bytes. If the input stream contains less than r bytes, it will be blocked until r bytes are read, or read the end of the input stream, or an I/O exception occurs.
In non-blocking mode, the read () method adopts the principle of how much data can be read and how much data can be read. the read () method reads read data from the current channel. It may be less than r capital or 0 bytes. The read () method always returns immediately, instead of waiting until the r bytes are read.
The number of actually read bytes returned by the read () method may be 0. If-1 is returned, it indicates that it has read to the end of the input stream.
Public int write (ByteBuffer src) throws IOException
Write the bytes in ByteBuffer specified by src to the Channel. assume that before the write () method is executed, the location of ByteBuffer is p, the remaining capacity is r, and r is equal to src. the return value of the remaining () method. assuming that the write () method actually writes n Bytes to the channel, then 0 ≤ n ≤ r. after the write () method is returned, the location of ByteBuffer referenced by the src Parameter Changes to p + n, and the limit remains unchanged, as shown in 4-12:
Figure 4-12 The write () method outputs n Bytes
In blocking mode, the write () method will strive to output r bytes. If the output buffer of the underlying network cannot accommodate r bytes, it will enter the blocking state until r bytes are output, or an I/O exception occurs.
In non-blocking mode, the write () method is based on the principle of outputting as much data as possible. It may be less than r bytes, or 0 bytes. write () the method always returns immediately, instead of waiting until the r bytes are output.
The write () method returns the actual number of output bytes, which may be 0.
8. Selector class
As long as the ServerSocketChannel and SocketChannel register specific events with the Selector, the Selector will monitor whether these events occur. the register () method of SelectableChannel registers events. This method returns a SelectionKey object that is used to track these registered events. a Selector object contains three types of SelectionKey sets.
All-keys set: the current collection of all selectionkeys registered with Selector. The keys () method of Selector returns this set. selected-keys set: the set of SelectionKey that has been captured by Selector. the selectedKeys () method of Selector returns the set. canceled-keys set: the set of canceled selectionkeys. selector does not provide a method to access this set.
The second and third sets are the subsets of the first set. For a newly created Selector object, the preceding set is empty.
When you execute the register () method of SelectableChannel, this method creates a SelectionKey and adds it to the all-keys set of Selector.
If you disable the Channel object associated with the SelectionKey object or call the cancel () method of the SelectionKey object, the SelectionKey object will be added to the canceled-keys set, this indicates that the SelectionKey object has been canceled. When the program executes the Selector select () method next time, the canceled SelectionKey object will be from all the sets (including the all-keys set, selected-keys set and canceled-keys set.
When the select () method of Selector is executed, if an event related to SelectionKey occurs, the SelectionKey will be added to the selected-keys set. the program can directly call the remove () method of the selected-keys set, or call the remove () method of its Iterator to delete a SelectionKey object from the selected-keys set.
The program cannot directly Delete the SelectionKey object in the all-keys set using the remove () method of the Set interface. if the program tries to do this, it will cause UnsupportedOperationException. (all-keys should be an internal class and do not implement the remove () method. The inherited object does not implement these methods. It may also be new HashSet () {override the remove () method and directly throw an exception}, for example, private static HashSet keys = new HashSet (){
Public boolean remove (Object o ){
Throw new UnsupportedOperationException ();
}
};)
The main method of the Selector class is as follows:
Public static Selector open () throws IOException
This is the static factory method of Selector. Create a Selector object.
Public boolean isOpen ()
Determine whether the Selector is open. After the Selector object is created, it is open. when the close () method of the Selector object is called, it is closed.
Public Set Keys ()
Returns the all-keys set of Selector, which contains all the SelectionKey objects associated with the Selector.
Public int selectNow () throws IOException
Returns the number of SelectionKey objects that have occurred in related events. This method uses a non-blocking working method to return the number of SelectionKey objects that have occurred in the current related time. If not, 0 is returned immediately.
Public int select () throws IOExceptionpublic int select (long timeout) throws IOException
This method uses the blocking method to return the number of SelectionKey objects that have occurred in the related event. If there is no one, it enters the blocking state until one of the following circumstances occurs () method.
> At least one SelectionKey event has occurred;
> Other threads call the Selector's wakeup () method, causing the thread executing the select () method to return immediately from the select () method.
> The thread executing the select () method is interrupted by other threads.
> The wait time is exceeded. this time is set by the timeout parameter of the select (long timeout) method, in milliseconds. if the wait times out, the system returns normally, but does not throw a timeout exception. if the program calls the select () method without parameters, it will never time out, which means that the thread that executes the select) method will never be interrupted because of timeout after it enters the blocking state.
Public Selector wakeup ()
Call the thread that executes the select () method of Selector (also set to the select (long timeout) method. when thread A executes the wakeup () method of the Selector object, if thread B is executing the select () method of the same Selector object, or thread B will execute the select () method of the Selector object after a while, then thread B will immediately return from the select () method when executing the select () method, without blocking. if thread B is blocked in the select () method, it will be immediately woken up and returned from the select () method.
The wakeup () method can only wake up the thread that executes the select () method once. if thread B is woken up when executing the select () method and is later executing the select () method, it will still work in blocking mode unless thread A calls the Selector object's wakeup () again () method.
Public void close () throws IOException
Disable Selector. if another thread is executing the Selector select () method and is in the blocking status, the thread will return immediately. the close () method releases all resources occupied by the Selector and cancels all selectionkeys associated with the Selector.
9. SelectionKey class
When ServerSocketChannel or SocketChannel registers an event with Selector through the register () method, the register () method creates a SelectionKey object, which is used to track the handle of the event registration. during the validity period of the SelectionKey object, the Selector will always monitor events related to the SelectionKey object. If the event occurs, the SelectionKey object will be added to the selected-keys collection. in the following cases, the SelectionKey object becomes invalid, meaning that the Selector will no longer monitor its related events:
(1) The program calls the cancel () method of SelectionKey;
(2) disable the Channel associated with SelectionKey;
(3) The Selector associated with the SelectionKey is disabled.
Four types of events are defined in SelectionKey, which are represented by four int constants.
SelectionKey. OP_ACCEPT: receives the connection readiness event, indicating that the server listens to the client connection and the server can receive the connection. the constant value is 16. (00010000) SelectionKey. OP_CONNECT: indicates that the connection between the client and the server has been established successfully. the constant value is 8. (00001000) SelectionKey. OP_READ: Read-ready event, which indicates that the channel has read data and can perform read operations. the constant value is 1. (00000001) SelectionKey. OP_WRITE: Write-ready event, indicating that data can be written to the channel. the constant value is 4. (00000100)
The preceding constants occupy different binary bits, so they can be combined in any way through the binary or operation "|". A SelectionKey object contains two types of events.
All events of interest: the interestOps () method of SelectionKey returns all events of interest. assume that the returned value is SelectionKey. OP_WRITE | SelectionKey. OP_READ indicates that this SelectionKey is interested in read-ready and write-ready events. the associated Selector object monitors these events. when an event is registered using the register () method of SelectableChannel, you can specify the event of interest to SelectionKey In the parameter. if the following code indicates that the new SelectionKey is interested in connection readiness and read readiness events:
SelectionKey key = socketChannel. register (selector, SelectionKey. OP_CONNECT | SelectionKey. OP_READ );
The interestOps (int ops) method of SelectionKey is used to add an event of interest to the SelectionKey object. If the following code adds an event of interest to the SelectionKey:
Key. interestOps (SelectionKey. OP_WRITE );
All events that have occurred: The readyOps () method of SelectionKey returns all events that have occurred. assume that the returned value is SelectionKey. OP_WRITE | SelectionKey. OP_READ indicates that the read-ready and write-ready events have occurred. This means that the SocketChannel object associated with this operation can be read and written.