NIO in blocking and non-blocking IO. NIO complete communications network

Blocking and non-blocking 

The traditional IO are blocking the flow. That is, when a thread calls read () or write (), the thread is blocked until there is some data to be read or written to, the thread in the meantime can not perform other tasks . Therefore, upon completion of the communication network IO operation, because the thread is blocked, so the server must have a separate thread for processing for each client, when the server needs to handle large number of clients, a sharp decline in performance.

 Java NIO is non-blocking mode. When the thread to read and write data from a channel, if no data is available, the thread can perform other tasks . The threads are usually non-blocking IO idle time for performing IO operations on other channels, so a separate thread to manage a plurality of input and output channels. Therefore, NIO allows the server to use one or a limited number of threads to simultaneously handle all client connections to the server

Completed using a network communication NIO

Blocking:

import org.junit.jupiter.api.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

public class BlockingNIOTest {
    @Test
    public void client() throws IOException {
        //获取通道
        SocketChannel sChannel=SocketChannel.open(new InetSocketAddress("127.0.0.1",9898));
        FileChannel inChannel=FileChannel.open(Paths.get("文件路径"),StandardOpenOption.READ);

        //分配指定大小的缓冲区
        ByteBuffer buf=ByteBuffer.allocate(1024);

        //读取本地文件,并发送到服务器
        while (inChannel.read(buf)!=-1){
            buf.flip();
            sChannel.write(buf);
            buf.clear();
        }

        //关闭通道
        sChannel.close();
        inChannel.close();
    }

    @Test
    public void server() throws IOException {
        //获取通道
        ServerSocketChannel ssChannel=ServerSocketChannel.open();
        FileChannel outChannel=FileChannel.open(Paths.get("文件路径"),StandardOpenOption.READ,StandardOpenOption.CREATE);

        //绑定9898端口连接
        ssChannel.bind(new InetSocketAddress(9898));
        //获取客户端连接的通道
        SocketChannel socketChannel=ssChannel.accept();
        //分配指定大小的缓冲区
        ByteBuffer buf=ByteBuffer.allocate(1024);
        //接收客户端的数据,并报错到本地
        while (socketChannel.read(buf)!=-1){
            buf.flip();
            outChannel.write(buf);
            buf.clear();
        }

        //关闭通道
        outChannel.close();
        ssChannel.close();
        socketChannel.close();
    }
}

 

Published 242 original articles · won praise 13 · views 10000 +

Guess you like

Origin blog.csdn.net/qq_41813208/article/details/103839560