Java NIO之網絡通信阻塞與非阻塞代碼實例(一)


相關Java NIO詳解:Java NIO詳解

代碼實例

一、單獨線程啓動客戶端與服務端(阻塞)
1.客戶端代碼


import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

//客戶端
public class NetworkSocket_client implements Runnable {

    /**
     * 單獨線程啓動客戶端測試
     * @throws IOException
     */
    @Test
    public void client() throws IOException {
        String clientFile="H:\\copyToFile\\aaa.log";
        NetworkSocket_client networkSocket_client=new NetworkSocket_client();
        networkSocket_client.netByBlockingNIO2Client(clientFile);
    }

    public void netByBlockingNIO2Client(String localFile) throws IOException {
        localFile="H:\\copyToFile\\aaa.log";
        //1.1.1獲取socket通道,地址和端口
        SocketChannel socketChannel1=SocketChannel.open(new InetSocketAddress("127.0.0.1",9090));
        //1.1.2獲取本地文件輸入通道
        FileChannel fileChannel1_in=FileChannel.open(Paths.get(localFile), StandardOpenOption.READ);

        //1.1.3 分配指定大小的緩衝區
        ByteBuffer byteBuffer1=ByteBuffer.allocate(1024);
        int i=1;
        //1.1.4讀取本地文件,併發送到服務端
        while(fileChannel1_in.read(byteBuffer1) !=-1){//將數據寫滿緩衝區,遍歷
            System.out.println("客戶端發送文件到服務端 "+i++);
            byteBuffer1.flip();//緩衝區反轉
            socketChannel1.write(byteBuffer1);//將緩衝區數據寫入socket通道
            byteBuffer1.clear();//讀完,清空緩衝區
        }

        //1.1.5 關閉通道
        socketChannel1.close();
        fileChannel1_in.close();
    }
}

2.服務端代碼


import org.junit.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.Paths;
import java.nio.file.StandardOpenOption;

//服務端
public class NetworkSocket_server implements Runnable {

    /**
     * 單獨線程啓動服務端測試
     * @throws IOException
     */
    @Test
    public void serverTest() throws IOException {
        String uploadFile="H:\\uploadFile\\bb.log";
        NetworkSocket_server networkSocket_server=new NetworkSocket_server();
        networkSocket_server.netByBlockingNIO2Server(uploadFile);
    }
    public void netByBlockingNIO2Server(String uploadFile) throws IOException {

        //1.2.1獲取通道
        ServerSocketChannel serverSocketChannel1=ServerSocketChannel.open();
        //1.2.2獲取本地文件
        FileChannel fileChannel2_out=FileChannel.open(Paths.get(uploadFile), StandardOpenOption.WRITE,StandardOpenOption.CREATE);

        //1.2.3 綁定連接,開放本地9090爲服務端口
        ServerSocketChannel bind = serverSocketChannel1.bind(new InetSocketAddress(9090));
        //1.2.4獲取客戶端連接的通道
        SocketChannel socketChannel1_client=serverSocketChannel1.accept();
        //1.2.5分配指定大小的緩衝區
        ByteBuffer byteBuffer1_server=ByteBuffer.allocate(1024);
        int i=1;
        //1.2.6接收客戶端的數據,並保存到本地
        while(socketChannel1_client.read(byteBuffer1_server) !=-1){
            System.out.println("服務端讀取文件保存本地"+i++);
            byteBuffer1_server.flip();
            fileChannel2_out.write(byteBuffer1_server);
            byteBuffer1_server.clear();
        }
        serverSocketChannel1.close();
        socketChannel1_client.close();
        fileChannel2_out.close();
    }
}

二、利用線程池管理客戶端和服務端(非阻塞)
1.客戶端代碼


import org.junit.Test;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

//客戶端
public class NetworkSocket_client implements Runnable {
    /**
     * 線程池啓動客戶端測試
     */
    @Override
    public void run() {
        try {
        Thread.sleep(2000);
            System.out.println("客戶端開啓。。。");
        String clientFile="H:\\copyToFile\\aaa.log";
        NetworkSocket_client networkSocket_client=new NetworkSocket_client();


            networkSocket_client.netByBlockingNIO2Client(clientFile);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void netByBlockingNIO2Client(String localFile) throws IOException {
        localFile="H:\\copyToFile\\aaa.log";
        //1.1.1獲取socket通道,地址和端口
        SocketChannel socketChannel1=SocketChannel.open(new InetSocketAddress("127.0.0.1",9090));
        //1.1.2獲取本地文件輸入通道
        FileChannel fileChannel1_in=FileChannel.open(Paths.get(localFile), StandardOpenOption.READ);

        //1.1.3 分配指定大小的緩衝區
        ByteBuffer byteBuffer1=ByteBuffer.allocate(1024);
        int i=1;
        //1.1.4讀取本地文件,併發送到服務端
        while(fileChannel1_in.read(byteBuffer1) !=-1){//將數據寫滿緩衝區,遍歷
            System.out.println("客戶端發送文件到服務端 "+i++);
            byteBuffer1.flip();//緩衝區反轉
            socketChannel1.write(byteBuffer1);//將緩衝區數據寫入socket通道
            byteBuffer1.clear();//讀完,清空緩衝區
        }

        //1.1.5 關閉通道
        socketChannel1.close();
        fileChannel1_in.close();
    }
}

2.服務端代碼


import org.junit.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.Paths;
import java.nio.file.StandardOpenOption;

//服務端
public class NetworkSocket_server implements Runnable {

    /**
     * 線程池啓動服務端測試
     */
    @Override
    public void run() {
        String uploadFile="H:\\uploadFile\\bb.log";
        NetworkSocket_server networkSocket_server=new NetworkSocket_server();
        try {
            System.out.println("服務端開啓。。。。");
            networkSocket_server.netByBlockingNIO2Server(uploadFile);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void netByBlockingNIO2Server(String uploadFile) throws IOException {

        //1.2.1獲取通道
        ServerSocketChannel serverSocketChannel1=ServerSocketChannel.open();
        //1.2.2獲取本地文件
        FileChannel fileChannel2_out=FileChannel.open(Paths.get(uploadFile), StandardOpenOption.WRITE,StandardOpenOption.CREATE);

        //1.2.3 綁定連接,開放本地9090爲服務端口
        ServerSocketChannel bind = serverSocketChannel1.bind(new InetSocketAddress(9090));
        //1.2.4獲取客戶端連接的通道
        SocketChannel socketChannel1_client=serverSocketChannel1.accept();
        //1.2.5分配指定大小的緩衝區
        ByteBuffer byteBuffer1_server=ByteBuffer.allocate(1024);
        int i=1;
        //1.2.6接收客戶端的數據,並保存到本地
        while(socketChannel1_client.read(byteBuffer1_server) !=-1){
            System.out.println("服務端讀取文件保存本地"+i++);
            byteBuffer1_server.flip();
            fileChannel2_out.write(byteBuffer1_server);
            byteBuffer1_server.clear();
        }
        serverSocketChannel1.close();
        socketChannel1_client.close();
        fileChannel2_out.close();
    }
}

3.創建線程池並啓動

package network_socket;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * 一、使用 NIO 完成網絡通信的三個核心:
 *
 * 1. 通道(Channel):負責連接
 *
 * 	   java.nio.channels.Channel 接口:
 * 			|--SelectableChannel
 * 				|--SocketChannel
 * 				|--ServerSocketChannel
 * 				|--DatagramChannel
 *
 * 				|--Pipe.SinkChannel
 * 				|--Pipe.SourceChannel
 *
 * 2. 緩衝區(Buffer):負責數據的存取
 *
 * 3. 選擇器(Selector):是 SelectableChannel 的多路複用器。用於監控 SelectableChannel 的 IO 狀況
 *
 */
public class NetworkSocketDemo {

    //main測試類
    public static void main(String[] args) {

        //1.阻塞NIO
        //客戶端
        NetworkSocket_client client=new NetworkSocket_client();
        //服務端
        NetworkSocket_server server=new NetworkSocket_server();

        ExecutorService executorService=Executors.newFixedThreadPool(2);
        ThreadPoolExecutor threadPoolExecutor= (ThreadPoolExecutor) executorService;
        executorService.execute(client);
        executorService.execute(server);
        executorService.shutdown();

    }
}

輸出結果

一、單獨線程啓動客戶端與服務端(阻塞),分別啓動客戶端和服務端代碼
客戶端文件先發送完之後,服務端菜開始讀取
在這裏插入圖片描述在這裏插入圖片描述二、利用線程池管理客戶端和服務端(非阻塞),運行線程池main方法
結果如下:
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章