【nio】nio阻塞模式

代码示例
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...");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

王佑辉

老板,赏点吧

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

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

打赏作者

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

抵扣说明:

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

余额充值