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方法
结果如下:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值