1 Basic introduction

Generally speaking NIO All in IO from Channel( passageway ) At the beginning .NIO The channel is similar to the flow , But some of the differences are as follows :

1. Channels can read or write , Flow is generally unidirectional ( You can only read or write , So before we did it with flow IO When operating, you need to create an input stream and an output stream respectively )

2. Channels can read and write asynchronously

3. Channels are always based on buffers Buffer Read and write

image.png

2 Channel Common class introduction

  1. Channel Interface constant use Of Channel Implementation class Yes :FileChannel , DatagramChannel ,ServerSocketChannel and SocketChannel .FileChannel Data reading and writing for files , DatagramChannel be used for UDP Reading and writing data of , ServerSocketChannel and SocketChannel be used for TCP Reading and writing data of .【ServerSocketChanne similar ServerSocket , SocketChannel similar Socket】

  2. SocketChannel And ServerSocketChannel     similar Socke and ServerSocket, It can complete the data communication between client and server .


image.png



3 ServerSocketChannel

Server implementation steps :

1. Open a server channel

2. Bind the corresponding port number

3. The channel is blocked by default , Need to be set to non blocking

4. Check if there is a client connection If there is a client connection, it will return to the corresponding channel

5. Get the data from the client , And put the data in byteBuffer In this buffer

6. Write data back to the client

7. Release resources

Code implementation :

package com.test.channel;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.ServerSocketChannel;

import java.nio.channels.SocketChannel;

import java.nio.charset.StandardCharsets;

/**

* Server side

*/

public class NIOServer {

  public static void main(String[] args) throws IOException,

InterruptedException {

    //1. Open a server channel

    ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

    //2. Bind the corresponding port number

    serverSocketChannel.bind(new InetSocketAddress(9999));

    //3. The channel is blocked by default , Need to be set to non blocking

    // true For channel blocking false Non blocking

    serverSocketChannel.configureBlocking(false);

    System.out.println(" Server started successfully ..........");

    while (true) {

      //4. Check if there is a client connection If there is a client connection, it will return to the corresponding channel , Otherwise return to null

      SocketChannel socketChannel = serverSocketChannel.accept();

      if (socketChannel == null) {

        System.out.println(" No client connection ... I'm going to do something else ");

        Thread.sleep(2000);

        continue;

     }

      //5. Get the data from the client , And put the data in byteBuffer In this buffer

      ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

      // Return value :

      // Positive numbers : Indicates the number of valid bytes read this time .

      //0  : Indicates that no valid bytes have been read this time .

      //-1 : It means to read to the end

      int read = socketChannel.read(byteBuffer);

      System.out.println(" Client message :" +

          new String(byteBuffer.array(), 0, read,

StandardCharsets.UTF_8));

      //6. Write data back to the client

      socketChannel.write(ByteBuffer.wrap(" no

money ".getBytes(StandardCharsets.UTF_8)));

      //7. Release resources

      socketChannel.close();

   }

 }

}

4 SocketChannel

Implementation steps

1. Open the channel

2. Set up the connection IP And port number

3. Writing data

4. Read the data written back by the server

5. Release resources

Code implementation :

package com.test.channel;

import java.io.IOException;

import java.net.InetSocketAddress;

import java.nio.ByteBuffer;

import java.nio.channels.SocketChannel;

import java.nio.charset.StandardCharsets;

/**

* client

*/

public class NIOClient {

  public static void main(String[] args) throws IOException {

    //1. Open the channel

    SocketChannel socketChannel = SocketChannel.open();

    //2. Set up the connection IP And port number

    socketChannel.connect(new InetSocketAddress("127.0.0.1", 9999));

    //3. Writing data

    socketChannel.write(ByteBuffer.wrap(" Boss , It's time to pay back

PULL !".getBytes(StandardCharsets.UTF_8)));

    //4. Read the data written back by the server

    ByteBuffer readBuffer = ByteBuffer.allocate(1024);

    int read=socketChannel.read(readBuffer);

    System.out.println(" Server message :" + new String(readBuffer.array(), 0, read,

StandardCharsets.UTF_8));

    //5. Release resources

    socketChannel.close();

 }

}

end ...