ServerSocketChannel let's start from the simplest ServerSocketChannel to discuss socket channel classes. ServerSocketChannel is a channel-based socket listener. It executes the same basic tasks as the familiar java.net. ServerSocket. However, it adds channel semantics and can run in non-blocking mode. Create a new ServerSocketChannel object using the static open () Factory method and return the same channel associated with the unbound java.net. ServerSocket. This peer ServerSocket can be obtained by calling the socket () method on the returned ServerSocketChannel. The ServerSocket object created as a ServerSocketChannel peer depends on the channel implementation. The SocketImpl associated with these sockets can recognize channels. The channel cannot be encapsulated outside a random socket object. Since ServerSocketChannel does not have the bind () method, it is necessary to retrieve the equivalent socket and use it to bind it to a port to start listening for connections. We also use the equivalent ServerSocket API to set other socket options as needed [java] ServerSocketChannel ssc = ServerSocketChannel. open (); ServerSocket serverSocket = ssc. socket (); // Listen on port 1234 serverSocket. bind (new InetSocketAddress (1234); same as its peer java.net. like ServerSocket, ServerSocketChannel also has the accept () method. Once you have created a ServerSocketChannel and bound it with a peering socket, you can call accept () on one of them (). If you choose to call the accept () method on ServerSocket, it performs the same behavior as any other ServerSocket: always blocking and returns a java.net. socket object (blocked !!!!). If you choose to call the accept () method on the ServerSocketChannel, The SocketChannel type object is returned, and the returned object can be run in non-blocking mode. Assume that the system already has a security manager, and both methods call the same security check. If it is called in non-blocking mode, when no incoming connection is waiting, ServerSocketChannel. accept () will immediately return null (because it is not blocked, so there must be a return ,). This capability of checking connections without blocking achieves scalability and reduces complexity. This is also possible. We can use a selector instance to register a ServerSocketChannel object to enable automatic notification upon new connection. Demonstrate how to use a non-blocking accept () method: [java] package com. anders. selector2; import java.net. inetSocketAddress; import java.net. serverSocket; import java. nio. byteBuffer; import java. nio. channels. serverSocketChannel; import java. nio. channels. socketChannel; public class ServerSocketChannelApp {private static final String MSG = "hello, I must be going \ n"; public static void main (String [] args) throws Exception {in T port = 8989; ServerSocketChannel ssc = ServerSocketChannel. open (); ServerSocket ss = ssc. socket (); ss. bind (new InetSocketAddress (port); // set no blocking ssc. configureBlocking (false); ByteBuffer buffer = ByteBuffer. wrap (MSG. getBytes (); while (true) {System. out. println ("wait for connection ...... "); SocketChannel SC = ssc. accept (); if (SC = null) {// no connections, snooze a while... thread. sleep (1000);} else {System. out. println ("Incoming connection from" + SC. socket (). getRemoteSocketAddress (); buffer. rewind (); // write msg to client SC. write (buffer); SC. close () ;}}} ps blocking and non-blocking traditional serversocket blocking mode: [java] public class ServerSocketApp {public static void main (String [] args) throws E Xception {ServerSocket ss = new ServerSocket (8989); ss. accept (); System. out. println (1) ;}} why does the program not output 1 ??? Because ServerSocket is in blocking mode, the accept method is blocked until there is a connection, therefore, when running the program, 1 is not output. If telnet is output, non-blocking in nio can be performed: [java] public static void main (String [] args) throws Exception {ServerSocketChannel ssc = ServerSocketChannel. open (); ServerSocket ss = ssc. socket (); ss. bind (new InetSocketAddress (8989); // set no blocking ssc. configureBlocking (false); ssc. accept (); System. out. println (1 );} Run this program with 1 Output !! This is because it is in non-blocking mode. SocketChannel [java] public abstract class SocketChannel extends AbstractSelectableChannel implements ByteChannel, ScatteringByteChannel, GatheringByteChannel {// This is a partial API listing public static SocketChannel open () throws IOException; public static SocketChannel open (InetSocketAddress remote) throws IOException; public abstract Socket socket (); public abstract boolean connect (SocketAd Dress remote) throws IOException; public abstract boolean isConnectionPending (); public abstract boolean finishConnect () throws IOException; public abstract boolean isConnected (); public final int validOps ();} the Socket and SocketChannel classes encapsulate point-to-point and ordered network connections, similar to the well-known and favorite TCP/IP network connections. The SocketChannel acts as a client to initiate a connection to the same listening server. Only after the connection is successful can it receive data and only receive each SocketChannel object from the connected address. Each SocketChannel object is created in a series of the same peer java.net. Socket object. The static open () method can create a new SocketChannel object, while the socket () method called on the newly created SocketChannel can return its equivalent Socket object; call the getChannel () method on the Socket to return the original SocketChannel. The newly created SocketChannel is opened but not connected. Attempting an I/O operation on an unconnected SocketChannel object causes NotYetConnectedException to be abnormal. We can connect this Socket channel by directly calling the connect () method on the channel or calling connect () on the socket object associated with the channel. Once a socket channel is connected, it will remain connected until it is closed. You can call the Boolean isConnected () method to test whether a SocketChannel is currently connected. [Java] The second type of open () with the InetSocketAddress parameter form is a convenient method to connect before returning. This code: SocketChannel socketChannel = SocketChannel. open (new InetSocketAddress ("somehost", somePort); equivalent to the following code: SocketChannel socketChannel = SocketChannel. open (); socketChannel. connect (new InetSocketAddress ("somehost", somePort); 1. If you choose to connect in the traditional way-call the connect () method on the peer Socket object, the traditional connection semantics will apply to this scenario. The thread will remain blocked before the connection is established or timeout expires. 2. If you choose to establish a connection by directly calling the connect () method on the channel and the channel is in blocking mode (default mode), the connection process is actually the same. There is no connect () method on SocketChannel that allows you to specify the timeout value. When the connect () method is called in non-blocking mode, SocketChannel provides concurrent connections: it initiates a connection to the request address and returns the value immediately. If the return value is true, the connection is established immediately (this may be a local loop back connection). If the connection cannot be established immediately, the connect () method returns false and continues the connection establishment process concurrently. It takes some time for the stream-oriented socket to establish the connection status, because the two systems to be connected must have a packet dialogue to establish the status information required to maintain the stream socket. Connecting to a remote system over an open Internet is time consuming. If a SocketChannel is currently connected by a concurrent connection, the isConnectPending () method returns true. Call the finishConnect () method to complete the connection process. This method can be safely called at any time. If you call the finishConnect () method on a non-blocking SocketChannel object, one of the following situations may occur: The explain connect () method has not been called. NoConnectionPendingException will occur. The pipeline connection is being established and has not been completed yet. If nothing happens, the finishConnect () method returns false immediately. After the consumer calls the connect () method in non-blocking mode, the SocketChannel is switched back to blocking mode. If necessary, the calling thread will be blocked until the connection is established. The finishConnect () method then returns the true value. After the consumer first calls connect () or the last call of finishConnect (), the connection establishment process has been completed. The internal status of the SocketChannel object will be updated to the connected status. The finishConnect () method returns the true value, and then the SocketChannel object can be used to transmit data. The ingress connection has been established. So nothing will happen. The finishConnect () method returns the true value. When the channel is in the intermediate connection-pending status, you can only call the finishConnect (), isConnectPending (), or isConnected () method. Once the connection is established successfully, isConnected () returns true. [Java] InetSocketAddress addr = new InetSocketAddress (host, port); SocketChannel SC = SocketChannel. open (); SC. configureBlocking (false); SC. connect (addr); while (! SC. finishConnect () {doSomethingElse ();} doSomethingWithChannel (SC); SC. close (); a piece of code available for managing asynchronous connections. [Java] public class SocketChannelApp {public static void main (String [] args) throws Exception {InetSocketAddress addr = new InetSocketAddress ("127.0.0.1", 8989); SocketChannel SC = SocketChannel. open (); SC. connect (addr); SC. configureBlocking (false); while (! SC. finishConnect () {doSomethings ();} // Do something with the connected socket ByteBuffer buffer = ByteBuffer. wrap (new String ("Hello server! "). GetBytes (); SC. write (buffer); SC. close ();} private static void doSomethings () {System. out. println (" do something useless! ") ;}} Server still uses the previous article. I changed it to [java] public class ServerSocketChannelApp {private static final String MSG =" hello, I must be going \ n "; public static void main (String [] args) throws Exception {int port = 8989; ServerSocketChannel ssc = ServerSocketChannel. open (); ServerSocket ss = ssc. socket (); ss. bind (new InetSocketAddress (port); // set no blocking ssc. configureBlocking (false); ByteBuffer bu Ffer = ByteBuffer. wrap (MSG. getBytes (); while (true) {// System. out. println ("wait for connection ...... "); SocketChannel SC = ssc. accept (); if (SC = null) {// no connections, snooze a while... thread. sleep (1000);} else {System. out. println ("Incoming connection from" + SC. socket (). getRemoteSocketAddress (); ByteBuffer readerBuffer = ByteBuffer. allocate (1, 1024); SC. read (readerBuffer); readerBuffer. flip (); // output get out (readerBuffer); buffer. rewind (); SC. write (buffer); SC. close () ;}} private s Tatic void out (ByteBuffer readerBuffer) {StringBuffer sb = new StringBuffer (); for (int I = 0; I <readerBuffer. limit (); I ++) {char c = (char) readerBuffer. get (); sb. append (new String (new char [] {c});} System. out. println (sb. toString () ;}} ps: if an asynchronous connection attempt fails, the next time you call finishConnect (), an appropriate checked exception is generated to indicate the nature of the problem. The channel is then closed and cannot be connected or used again. Connection-related methods allow us to poll a channel and determine its status during connection. In chapter 4, we will learn how to use selector to avoid polling and receive notifications after an asynchronous connection is established. The Socket channel is thread-safe. During Concurrent access, no special measures are required to protect multiple threads that initiate the access. However, at any time, only one read operation and one write operation are in progress. Remember that sockets is stream-oriented, not packet-oriented. They ensure that the sent bytes arrive in sequence, but cannot guarantee to maintain the byte group. A sender may write 20 bytes to a socket, but the receiver only receives 3 bytes when calling the read () method. The remaining 17 bytes are still in transmission. For this reason, it is not a good design to allow multiple threads that do not cooperate to share the same side of a stream socket. The connect () and finishConnect () methods are synchronized with each other, and as long as one of the operations is in progress, any read or write method calls will be blocked, even in non-blocking mode. If you have any questions or cannot afford to block a read or write operation on a channel, use the isConnected () method to test the connection status.