This article uses Java 10.0.1 installed on WIN10.
Last time I made a BIO transfer path, today I will continue to implement NIO.
Simply put, it doesn't block I / O requests. You can improve existing I / O processing (BIO).
First, for the request from the client side, two parts, a connection request and an I / O request, are included. Connection requests are always made, but I / O requests are made from time to time. Therefore, the method of preparing one processing thread regardless of one request regardless of whether or not there is I / O processing such as BIO wastes the performance of the server.
NIO has only one processing thread for every request from the client side. If there is an I / O request, ask another thread for I / O processing.
*** SocketChannel *** and *** ServerSocketChannel *** are provided from the Java language, so this time I will try to implement TCP / IP + NIO using these. (Official API is here: SocketChannel, [ServerSocketChannel](https://docs .oracle.com/javase/jp/8/docs/api/java/nio/channels/ServerSocketChannel.html) Server side files
** Contents of ChannelServer.java **
public class ChannelServer {
    public static void main(String[] args) throws IOException {
        // I/Prepare a thread pool to process O requests
        ThreadPoolExecutor executor = new ThreadPoolExecutor(3, 10, 1000, TimeUnit.MILLISECONDS, 
                new ArrayBlockingQueue<Runnable>(100));
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(1234));
        while (true) {
            SocketChannel socketChannel = serverSocketChannel.accept();
            if (socketChannel != null) {
                //Commit the request to the thread pool
                executor.submit(new ChannelServerThread(socketChannel));
            }
        }
    }
}
** Contents of ChannelServer.java **
*** Thread to process request ***
public class ChannelServerThread implements Runnable {
    private SocketChannel socketChannel;
    private String remoteName;
    public ChannelServerThread(SocketChannel socketChannel) throws IOException {
        this.socketChannel = socketChannel;
        this.remoteName = socketChannel.getRemoteAddress().toString();
        System.out.println("client:" + remoteName + " access successfully!");
    }
    // I/Handle O request
    @Override
    public void run() {
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
        StringBuilder sb = new StringBuilder();
        byte b[];
        //Read data and length from socketChannel and output to standard output
        while(true) {
            try {
                sizeBuffer.clear();
                int read = socketChannel.read(sizeBuffer);
                if (read != -1) {
                    sb.setLength(0);
                    sizeBuffer.flip();
                    int size = sizeBuffer.getInt();
                    int readCount = 0;
                    b = new byte[1024];
                    while (readCount < size) {
                        buffer.clear();
                        read = socketChannel.read(buffer);
                        if (read != -1) {
                            readCount += read;
                            buffer.flip();
                            int index = 0 ;
                            while(buffer.hasRemaining()) {
                                b[index++] = buffer.get();
                                if (index >= b.length) {
                                    index = 0;
                                    sb.append(new String(b,"UTF-8"));
                                }
                            }
                            if (index > 0) {
                                sb.append(new String(b,"UTF-8"));
                            }
                        }
                    }
                    System.out.println(remoteName +  ":" + sb.toString());
                }
            } catch (Exception e) {
                System.out.println(remoteName + "access colsed");
                try {
                    socketChannel.close();
                } catch (IOException ex) {
                }
                break;
            }
        }
    }
}
** Client-side files **
*** Creates a socketChannel and accesses the specified server and port ***
public class ChannelClient {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(1234));
        while (true) {
            Scanner sc = new Scanner(System.in);
            String next = sc.next();
            sendMessage(socketChannel, next);
        }
    }
    //Prepare a container for Channel to IPO
    public static void sendMessage(SocketChannel socketChannel, String mes) throws IOException {
        if (mes == null || mes.isEmpty()) {
            return;
        }
        byte[] bytes = mes.getBytes("UTF-8");
        int size = bytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(size);
        ByteBuffer sizeBuffer = ByteBuffer.allocate(4);
        sizeBuffer.putInt(size);
        buffer.put(bytes);
        buffer.flip();
        sizeBuffer.flip();
        ByteBuffer dest[] = {sizeBuffer,buffer};
        while (sizeBuffer.hasRemaining() || buffer.hasRemaining()) {
            socketChannel.write(dest);
        }
    }
}
*** Starting the server and waiting for a connection: ***
server
PS C:\Users\ma\Documents\work\socket\nio_tcp> java ChannelServer
*** Launch clients 1 and 2 respectively and enter something: ***
** Client 1 **
PS C:\Users\ma\Documents\work\socket\nio_tcp> java ChannelClient
iamfirstuser!
byebyefirstone!
Exception in thread "main"
PS C:\Users\ma\Documents\work\socket\nio_tcp>
** Client 2 **
java ChannelClient
iamseconduser
byebyesecondone!
Exception in thread "main"
PS C:\Users\ma\Documents\work\socket\nio_tcp>
server
PS C:\Users\ma\Documents\work\socket\nio_tcp> java ChannelServer
client:/192.168.56.1:50138 access successfully!
client:/192.168.56.1:50139 access successfully!
/192.168.56.1:50138:iamfirstuser!
/192.168.56.1:50139:iamseconduser
/192.168.56.1:50138:byebyefirstone!
/192.168.56.1:50138access colsed
/192.168.56.1:50139:byebyesecondone!
/192.168.56.1:50139access colsed
This time, I made a TCP / IP + NIO transfer path using Java's SocketChannel and ServerSocketChannel libraries. We were also able to authenticate that one server can handle multiple requests at the same time.
Recommended Posts