零基础java自学流程-Java语言高级533

这个Java代码示例展示了如何使用NIO(非阻塞I/O)创建一个服务器,通过Selector进行轮询监听客户端连接、读取数据。在`listenSelector()`方法中,`this.selector.selectNow()`用于非阻塞地检查事件,`handler(key)`处理连接请求和读取请求。整个程序旨在提供一种高效、低延迟的服务端I/O处理方式。

Java的NIO代码

this.selector.select(); 在这里会阻塞,无论是客户端连接还是客户端发送数据还是客户端关闭,这里都会触发。虽然这里是单线程,但是底层处理用到了线程池。

 
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.*;
import java.util.Iterator;

/**
 * 阻塞点this.selector.select();
 * 轮询器虽然是一个线程内部也是线程池
 */
public class NioSocket {
    private Selector selector;   //通道管理器(管理器)

    /**
     * 初始化Channel并绑定端口
     * @param port
     * @throws IOException
     */
    public void initServer(int port) throws IOException {
        ServerSocketChannel serverChannel = ServerSocketChannel.open();
        serverChannel.configureBlocking(false);  //非阻塞
        serverChannel.socket().bind(new InetSocketAddress(port));

        this.selector = Selector.open();
        serverChannel.register(selector, SelectionKey.OP_ACCEPT);
        System.out.println("服务器已启动...");
    }

    /**
     * 监听轮询器
     * @throws IOException
     */
    public void listenSelector() throws IOException {
        //轮询监听selector
        while (true){
            //等待客户连接
            //select模型,多路复用
            //this.selector.select();   //在这里会阻塞,无论是连接还是客户端发送数据还是客户端关闭,这里都会触发
            this.selector.selectNow();   //这里不阻塞会立即执行
            Iterator<SelectionKey> iteKey = this.selector.selectedKeys().iterator();
            while (iteKey.hasNext()){
                SelectionKey key = iteKey.next();
                iteKey.remove();  //移除,防止重复处理
                //处理请求
                handler(key);
            }
        }
    }

    /**
     * 处理客户端请求
     * @param key
     */
    private void handler(SelectionKey key) throws IOException {
        if (key.isAcceptable()){  //处理连接请求
            //处理客户端连接请求事件
            ServerSocketChannel serverChannel = (ServerSocketChannel) key.channel();
            SocketChannel socketChannel = serverChannel.accept();
            //接受客户端发送的信息时,需要给通道设置读权限
            socketChannel.configureBlocking(false);
            socketChannel.register(selector,SelectionKey.OP_READ);
        }else if(key.isReadable()){   //处理读请求
            //处理读事件
            SocketChannel socketChannel = (SocketChannel) key.channel();
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int readData = socketChannel.read(buffer);
            if (readData>0){
                String info  = new String(buffer.array(),"GBK").trim();
                System.out.println("服务端收到数据: "+Thread.currentThread()+info);
            }else {
                System.out.println("客户端关闭了...");
                key.cancel();
            }
        }
    }

    public static void main(String[] args) throws IOException {
        NioSocket nio = new NioSocket();
        nio.initServer(8888);
        nio.listenSelector();
    }
}
 


 尚学堂给同学们带来全新的Java300集课程啦!java零基础小白自学Java必备优质教程_手把手图解学习Java,让学习成为一种享受_哔哩哔哩_bilibili尚学堂给同学们带来全新的Java300集课程啦本课程为Java300集2022版第一季,配合最新版的Java课程,所有视频重新录制,课件所有图形做了重新绘制和配色,图解学习Java,让学习成为一种享受本套教程专门为零基础学员而制,适合准备入行Java开发的零基础学员,视频中穿插多个实战项目。每一个知识点都讲解的通俗易懂,由浅入深。不仅适用于零基础的初学者,有经验的程序员也可做巩固学习。后续课https://www.bilibili.com/video/BV1qL411u7eE?spm_id_from=333.999.0.0

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值