java-nio-server聊天室服务端

2022-3-13 diaba IO

package com.jiucaiyuan.net.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

/**
 * @Author jiucaiyuan  2022/3/12 23:47
 * @mail services@jiucaiyuan.net
 */

public class Server {

    public static void main(String[] args) throws IOException {
        //1 获取通道
        ServerSocketChannel ssChannel = ServerSocketChannel.open();
        //2 切换为非阻塞模式
        ssChannel.configureBlocking(false);
        //3 绑定链接端口
        ssChannel.bind(new InetSocketAddress(9999));
        //4 获取选择器
        Selector selector = Selector.open();
        //5 通道注册到选择器上,并且制定监听接收事件
        ssChannel.register(selector, SelectionKey.OP_ACCEPT);
        //6 使用Selector选择器轮训已经就绪好的事件
        while (selector.select()>0){
            //7 获取选择器中的所有注册的通道中已经就绪好的事件
            Iterator<SelectionKey> it = selector.selectedKeys().iterator();
            //8 开始便利这些准备好的事件
            while (it.hasNext()){
                //9 提取当前这个事件
                SelectionKey sk = it.next();
                //10 判断当前这个事件具体是什么
                if(sk.isAcceptable()){
                    //11 获取当前接入的客户端通道
                    SocketChannel socketChannel = ssChannel.accept();
                    //12 转换成非阻塞
                    socketChannel.configureBlocking(false);
                    //13 把本客户端注册到选择器上
                    socketChannel.register(selector,SelectionKey.OP_READ);
                }else if (sk.isReadable()){
                    //14 获取当前选择器上的读就绪事件
                    SocketChannel socketChannel = (SocketChannel)sk.channel();
                    //15 读取数据
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    int len = 0;
                    while ((len = socketChannel.read(byteBuffer))>0){
                        //切换缓存处理方式
                        byteBuffer.flip();
                        System.out.println(new String(byteBuffer.array(),0,len));
                        //清楚已处理数据
                        byteBuffer.clear();
                    }
                }
                //移除处理完毕的事件(标记已处理)
                it.remove();
            }
        }
    }
}




	

发表评论:

Powered by emlog 京ICP备15045175号-1 Copyright © 2022