【nio】nio阻塞模式

导读:本篇文章讲解 【nio】nio阻塞模式,希望对大家有帮助,欢迎收藏,转发!站点地址:www.bmabk.com

代码示例

1.server端
package com.learning.block;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.ArrayList;
import java.util.List;

import static com.learning.bytebuffer.ByteBufferUtil.debugRead;

/**
 * @Author wangyouhui
 * @Description
 **/
@Slf4j
public class Server {
    public static void main(String[] args) throws IOException {
        // 使用nio来理解阻塞模式
        // 0.ByteBuffer
        ByteBuffer byteBuffer = ByteBuffer.allocate(16);
        // 1.创建服务器
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // 2.绑定监听端口
        serverSocketChannel.bind(new InetSocketAddress(8080));
        // 3.连接集合
        List<SocketChannel> socketChannelList = new ArrayList<>();
        // 与多个客户端连接
        while(true){
            // 4.accept,建立与客户端的连接
            log.info("connecting...");
            // 阻塞方法,线程停止运行
            SocketChannel socketChannel = serverSocketChannel.accept();
            log.info("connected...{}", socketChannel);
            socketChannelList.add(socketChannel);
            for(SocketChannel channel : socketChannelList){
                // 5.接收客户端发送的数据
                log.info("before read...{}", channel);
                // 阻塞方法,线程停止运行
                channel.read(byteBuffer);
                // 切换到读模式
                byteBuffer.flip();
                debugRead(byteBuffer);
                byteBuffer.clear();
                log.debug("after read...{}", channel);
            }
        }
    }
}
2.client端
package com.learning.block;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.channels.SocketChannel;

/**
 * @Author wangyouhui
 * @Description 
 **/
public class Client {
    public static void main(String[] args) throws IOException {
        SocketChannel sc = SocketChannel.open();
        sc.connect(new InetSocketAddress("localhost", 8080));
        System.out.println("waiting...");
    }

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。

文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/92325.html

(0)
小半的头像小半

相关推荐

极客之音——专业性很强的中文编程技术网站,欢迎收藏到浏览器,订阅我们!