Java_nio _ non-blocking communication

Source: Internet
Author: User

Java_nio _ non-blocking communication
1. Commonly Used classes that support non-blocking communication

    ServerSocketChannel: an alternative to ServerSocket. It supports blocking communication and non-blocking communication. socketChannel: A Socket replacement class that supports blocking communication and non-blocking communication. selector: receives connection readiness events for ServerSocketChannel monitoring, and monitors connection readiness, read readiness, and write readiness events for SocketChannel. selectionKey: indicates the handle for registering events from ServerSocketChannel and SocketChannel to Selector. when a SelectionKey object is located in the selected-keys set of the Selector object, it indicates that the event related to this SelectionKey object has occurred.

    Both ServerSocketChannel and SocketChannel are subclasses of SelectableChannel, as shown in 4-3. The SelectableChannel class and its subclasses can delegate Selector to monitor some of their possible events. This delegation process is also called the registration event process.

    Figure 4-3 block diagram of the SelectableChannel class and its subclass

    The ServerSocketChannel code registers with Selector to receive connection readiness events is as follows:

    SelectionKey key = serverSocketChannel. register (selector, SelectionKey. OP_ACCEPT );

    Some static constants in the SelectionKey class indicate the event type,ServerSocketChannelOnly one event may occur.

      SelectionKey. OP_ACCEPT: receives connection readiness events, indicating At least one customer connection exists., ServerThis connection can be received.

      SocketChannelThe following three events may occur.

        SelectionKey. OP_CONNECT: indicates that the connection between the client and the server has been established successfully. selectionKey. OP_READ: Read-ready event, which indicates that the input stream already has readable data and the SelectionKey can be read. OP_WRITE: Write-ready event, indicating that data can be written to the input stream.

        SocketChannel provides methods for receiving and sending data.

          Read (ByteBuffer buffer): receives data and stores them in the ByteBuffer specified by the parameter. write (ByteBuffer buffer): sends the data in the ByteBuffer specified by the parameter.

          ByteBuffer indicates the byte buffer. The read () and write () Methods of SocketChannel manipulate ByteBuffer. the ByteBuffer class inherits from the Buffer class. byteBuffer stores bytes. In order to convert them into strings, The Charset class is also required. The Charset class represents character encoding. It provides the function of converting bytes into strings (decoding process) and converts a string to a byte stream (encoding process.


          2. Buffer

          Data input and output are usually time-consuming operations. The buffer improves the efficiency of I/O operations in two aspects:

            Reduces the actual number of physical reads and writes. The cache area is allocated with memory when it is created, and the memory area is reused all the time. This can reduce the number of dynamic memory areas allocated and recycled.

            Old I/O class library (corresponding to java. bufferedInputStream, BufferedOutputStream, BufferedReader, and BufferedWriter In the nio package) use the buffer zone in their implementation. java. the nio package exposes the Buffer API so that Java programs can directly control and use the Buffer. 4-4 shows the Buffer class hierarchy.

            Figure 4-4 Buffer class hierarchy

            All buffers have the following attributes:

              Capacity: The amount of data that can be stored in the buffer. limit: the current end point of the buffer. You cannot perform read/write operations on areas beyond the limit in the buffer. the limit can be modified, which facilitates the reuse of the buffer zone. for example, assuming that the buffer with a capacity of 100 has filled up the data, then when the program re-uses the buffer, it only writes 10 new data into the buffer zone from the position 0 to 10, in this case, you can set the limit to 10 so that you cannot read the previous data. the limit is a non-negative integer and should not be greater than the capacity. position: the position of the next read/write unit in the buffer zone. This value is changed each time the data in the buffer zone is read and written to prepare for the next read/write. the position is a non-negative integer and should not be greater than the limit.

              4-5, the relationship between the above three attributes is: Capacity ≥ limit ≥ position ≥ 0

              Figure 4-5 three attributes of the buffer

              The buffer zone provides a method to change the preceding three attributes.

                Clear (): sets the limit to the capacity, and then sets the position to 0; flip (): sets the limit to the position, and then sets the position to 0; rewind (): set the position to 0 without changing the limit.

                The remaining () method of the Buffer class returns the remaining Buffer capacity. The value is equal to the limit-position. the compact () method of the Buffer class deletes the content from 0 to the current position in the Buffer, and then copies the content from the current position to the limit to the range from 0 to limit-position, the values of the current position and the limit are also changed, as shown in 4-6.

                Figure 4-6 effect of Buffer class compact ()

                Java. nio. the Buffer class is an abstract class and cannot be instantiated. there are eight specific buffer classes, the most basic of which is ByteBuffer, which stores data units in bytes. the ByteBuffer class does not provide public constructor methods, but provides two static factory methods for obtaining ByteBuffer instances.

                  Allocate (int capacity): returns a ByteBuffer object. The capacity parameter specifies the buffer capacity. directAllocate (int capacity): returns a ByteBuffer object. The parameter capacity specifies the buffer capacity. the buffer returned by this method is called a direct buffer, which can be better coupled with the current operating system, thus further improving the I/O operation speed. however, the system overhead of allocating a buffer directly is very large. Therefore, this buffer is used only when the buffer is large and long-lived or needs to be reused frequently.

                  In addition to the boolean type, each basic type has a corresponding buffer class, including CharBuffer, DoubleBuffer, FloatBuffer, IntBuffer, LongBuffer, and writable buffer. each of these buffer classes has a static factory method allocate (int capacity) that can return its own instance ). data Units in CharBuffer are characters, while those in DoubleBuffer are double data units. another buffer is MappedByteBuffer, which is a subclass of ByteBuffer. mappedByteBuffer can directly map the buffer zone to a certain area of the file.

                  All buffer classes provide read/write buffer methods:

                    Get (): relative read. read the data of a unit from the current position of the buffer, and Add 1 to the position after reading; get (int index): absolute read. reads the data of a unit from the location specified by the index parameter; put (): relative write. write the data of a unit to the current position of the buffer, and Add 1 to the position after writing; put (int index): absolute write. write the data of a unit to the location specified by the index parameter.
                    3. character encoding Charset

                    Java. nio. each instance of the Channel class represents a specific character encoding type. as shown in 4-7, the process of converting a byte sequence to a string is called decoding. The process of converting a string to a byte sequence is called encoding.

                    Figure 4-7 encoding and decoding

                    The Charset class provides the encoding and decoding methods:

                      ByteBuffer encode (String str): encode the String specified by the Str parameter, store the obtained ByteBuffer sequence in a ByteBuffer object, and return it. ByteBuffer encode (CharBuffer cb ): encode the characters in the character buffer specified by the cb parameter, store the obtained byte sequence in a ByteBuffer object, and return it; CharBuffer decode (ByteBuffer bb ): decodes the ByteBuffer sequence specified by the bb parameter, stores the obtained Character Sequence in a CharBuffer object, and returns it.

                      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.


                      4. Channel

                      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.

                      Figure 4-8 functions of the channel

                      4-9 shows the main layer of the Channel.

                      Figure 4-9 main Channel hierarchy

                      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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.