三种IO模型

三种IO模型

在这里插入图片描述

BIO简单代码实现

服务器端
public class SocketBioServer {
    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(9001);
        while (true) {
            System.out.println("服务器端正在等待连接中...");
            // 阻塞方法 如果没有客户端与服务器端建立连接时,该方法会阻塞等待
            final Socket socket = serverSocket.accept();
            System.out.println("有客户端和我连接啦");
            //如果不使用异步线程处理接受io操作的情况下,有可能会阻塞等待 无法接受新的连接请求。
            new Thread(() -> {
                try {
                    handler(socket);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }).start();
//            handler(socket);
        }
    }

    private static void handler(Socket socket) throws IOException {
        System.out.println("线程id= " + Thread.currentThread().getId());
        byte[] bytes = new byte[1024];

        System.out.println("开始read。。");
        //接收客户端的数据,如果没有读取到客户端数据时,该方法也会阻塞
        int read = socket.getInputStream().read(bytes);
        System.out.println("read结束");
        if (read != -1) {
            System.out.println("接收到客户端的数据:" + new String(bytes, 0, read));
            System.out.println("线程id= = " + Thread.currentThread().getId());

        }
        socket.getOutputStream().write("效果演示完毕~~".getBytes());
        socket.getOutputStream().flush();
    }
}
客户端
public class SocketBioClient {

    public static void main(String[] args) throws IOException {
        Socket socket = new Socket("127.0.0.1", 9001);
        //向服务端发送数据
        socket.getOutputStream().write("来演示下同步阻塞Bio".getBytes());
        socket.getOutputStream().flush();
        System.out.println("向服务端发送数据结束");
        byte[] bytes = new byte[1024];
        //接收服务端回传的数据
        socket.getInputStream().read(bytes);
        System.out.println("接收到服务端的数据:" + new String(bytes));
        socket.close();
    }
}

NIO简单代码实现

服务器端
public class SimulationNioTcpServer {

    /**
     * 保存SocketChannel
     */
    private static List<SocketChannel> listSocketChannel = new ArrayList<>();
    /**
     * 缓冲区大小
     */
    private static ByteBuffer byteBuffer = ByteBuffer.allocate(512);

    public static void main(String[] args) {
        try {
            // 1.创建一个ServerSocketChannel
            ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
            // 2. 绑定地址
            ServerSocketChannel bind = serverSocketChannel.bind(new InetSocketAddress(8080));
            // 3.设置非阻塞模式
            serverSocketChannel.configureBlocking(false);
            while (true) {
                // 4.等待建立连接  如果设置非阻塞的情况下,如果没有获取连接的情况下直接返回null,如果建立连接之后返回socketChannel
                // 建立三次握手
                SocketChannel socketChannel = serverSocketChannel.accept();
                // 5. 如果socketChannel 不为空的情况下,则将该连接保存起来。
                if (socketChannel != null) {
                    // 设置该socketChannel通道为fasle
                    socketChannel.configureBlocking(false);
                    listSocketChannel.add(socketChannel);
                }
                // 循环SocketChannel,检查每个SocketChannel中数据有传输数据
                for (SocketChannel scl : listSocketChannel) {
                    try {
                        // 6.以缓冲区方式读取
                        int read = scl.read(byteBuffer);
                        if (read > 0) {
                            byteBuffer.flip();
                            // 转换格式为中文的格式
                            Charset charset = Charset.forName("UTF-8");
                            String receiveText = charset.newDecoder().decode
                                    (byteBuffer.asReadOnlyBuffer()).toString();
                            System.out.println("receiveText:" + receiveText);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

-------资源转载于蚂蚁课堂(www.mayikt.com)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

魔力小猪

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值