Netty,认识和深入(三),JAVA原生NIO认识

Netty,认识和深入(三),JAVA原生NIO认识,第1张

NIO 基本介绍

JAVA NIO:同步非阻塞,服务器实现模式为一个线程处理多个请求(连接),即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求就进行处理;

JAVA NIO 全称 JAVA non-blocking IO,是指JDK 提供的新的API。


从JDK1.4开始,JAVA提供了一系列改进的输入/输出的新特性,被统称为NIO(即 New IO),是同步阻塞的

NIO 相关类都被放在 java.nio 包及子包下,并且对原java.io 包中的很多类进行改写。


NIO 有三大核心部分: Channel(通道),Buffer(缓冲区),Selector(选择器)

NIO 是面向缓冲区,或者面向块编程的,数据读取到一个它稍微处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络。


JAVA NIO 的非阻塞模式,使一个线程从某通道发送请求或者读取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是保持线程阻塞,所以直至数据变的可以读取之前,该线程可以继续做其他事情。


非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时去做别的事情。


NIO 是可以做到用一个线程来处理多个 *** 作的,假设有10000个请求过来,根据实际情况,可以分配50或者100个线程来处理,不像之前的阻塞IO那样,非得分配10000个。


HTTP2.0 使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数据比HTTP1.1大了好几个数量级

NIO 方式适用于连接数目较多且连接比较短的架构,比如聊天服务器,d幕系统,服务器间通讯等。


编程比较复杂,JDk1.4开始支持

大致流程图如下:

总结

BIO 以流的方式处理的数据,而NIO以块的方式处理数据,块I/O 基于Channel (通道)和 Buffer(缓冲区)进行 *** 作,数据总是从通道读取到缓冲区,或者从缓冲区写入到通道中。


selector(选择器)用于监听多个通道的事件,(不如连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道。


NIO三大核心

NIO的 selector,Channel,Buffer,关系简单示意图:

  • 每一个Channel 对应一个Buffer;

  • Selector 对对应一个线程,一个线程对应多个channel;

  • 有三个 Channel 注册到 该selector 程序中;

  • 程序切换到哪个channel 是有事件决定的,Event 就是一个重要的概念;

  • Selector 会根据不同的事件,在各个通道上切换;

  • Buffer 就是内存块,底层是有一个数组;

  • 数据的读取写入是通过Buffer,这个和BIO,BIO中要么是输入流,或者是输出流,不能双向,但是NIO的Buffer 是可以读也可以写,需要flip()方法切换

  • Channel 是双向的,可以返回底层 *** 作系统的情况,比如Linux,底层的 *** 作系统通道就是双向的;

Buffer(缓冲区) 基本介绍

缓冲区(Buffer): 缓冲区本质上是一个可以读写数据的内存块,可以理解成是一个容器对象(含数组),该对象提供了一组方法,可以更轻松地使用内存块,缓冲区对象内置了一些机制,能够跟踪和记录缓冲区的状态变化情况,Channel提供从文件,网络读取数据的渠道,但是读取或写入数据都必须经由Buffer。


源码重要属性

Buffer 类定义了所有的缓冲区都具有的四个属性来提供关于其所包含的数据元素的信息;

属性描述
capacity容量,即可以容纳的最大数据量,在缓冲区创建时被设定并且不能改变
limit表示缓冲区的当前终点,不能对缓冲区超过极限的位置进行读写 *** 作,且极限是可以修改的
position位置,下一个要被读写的元素的索引,每次读写缓冲区数据都会改变改值,为下次读写做准备
mark标记

buffer底层的数据结构都是一个数组,然后通过 上面的四个属性来控制数据的存储和读取,以及api中的属性 控制只读等。



JAVA代码示例一:

package com.kelecc.nio;

import java.nio.IntBuffer;

/**
 * 功能描述: Buffer Demo
 *
 * @Author keLe
 */
public class BasicBuffer {

    public static void main(String[] args) {
        //举例说明buffer 的使用
        //创建Buffer,大小为5,即可以存放5个int
        IntBuffer allocate = IntBuffer.allocate(5);

        //向buffer 存放数据
        allocate.put(10);
        allocate.put(11);
        allocate.put(12);
        allocate.put(13);
        allocate.put(14);

        //从buffer 读取数据
        // 读写切换,反转重置position 和limit 的长度
        allocate.flip();
        while (allocate.hasRemaining()){
            System.out.println(allocate.get());
        }
    }
}

java代码示例二:

package com.kelecc.nio;

import java.nio.IntBuffer;

/**
 * 功能描述: Buffer Demo
 *
 * @Author keLe
 */
public class BasicBuffer {

    public static void main(String[] args) {
        //举例说明buffer 的使用
        //创建Buffer,大小为5,即可以存放5个int
        IntBuffer allocate = IntBuffer.allocate(5);

        //向buffer 存放数据
        allocate.put(10);
        allocate.put(11);
        allocate.put(12);
        allocate.put(13);
        allocate.put(14);
        //表示读的元素只有两个,缓冲区的终点不能超过三个
        allocate.position(2);
        allocate.limit(3);
        //从buffer 读取数据
        // 读写切换,反转
        allocate.flip();
        while (allocate.hasRemaining()){
            System.out.println(allocate.get());
        }
    }
}

拷贝
public class NioFileChannelDemo4 {
    public static void main(String[] args) {
        try (
                FileInputStream  fileInputStream = new FileInputStream("d:\file.txt");
                FileChannel fileInputStreamChannel = fileInputStream.getChannel();
                FileOutputStream fileOutputStream = new FileOutputStream("d:\fileNew.txt");
                FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

        ) {
            //拷贝
            fileOutputStreamChannel.transferFrom(fileInputStreamChannel, 0, fileInputStreamChannel.size());
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
MappedBuffer

可让文件直接在内存(堆外内存)修改, *** 作系统不需要拷贝一次

代码示例:

public class MappedBufferDemo {
    public static void main(String[] args) {
        try (RandomAccessFile randomAccessFile = new RandomAccessFile("D:\file.txt", "rw")) {
            FileChannel channel = randomAccessFile.getChannel();

            //参数1 :使用读写模式
            //参数2 :可以修改的起始位置
            //参数3 :是映射到内存的大小,即将1.txt 的多少个字节隐射到内存 可以直接修改的范围就是 0到文件的长度
            MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, channel.size());
            mappedByteBuffer.put(0,(byte)'A');
            mappedByteBuffer.put(1,(byte)'2');
            System.out.println("修改成功");
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
分散,聚集

Scattering 将 buffer 写入时,可以采用Buffer数组,依次写入 [分散]

Gathering 从Buffer读取数据时,可以采用Buffer数组,依次读[聚集]

代码示例:

package com.kelecc.nio;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Arrays;

/**
 * 功能描述: buffer的 分散和聚集
 *  Scattering 将 buffer 写入时,可以采用Buffer数组,依次写入 [分散]
 *
 *  Gathering  从Buffer读取数据时,可以采用Buffer数组,依次读[聚集]
 *
 * @Author keLe
 */
public class ScatteringAndGatheringDemo {
    public static void main(String[] args) throws IOException {

        //使用ServerSocketChannel 和 SocketChannel 网络
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //绑定端口到socket 并启动
        serverSocketChannel.socket().bind(inetSocketAddress);

        //创建buffer 数组
        ByteBuffer[] byteBuffers = new ByteBuffer[2];
        byteBuffers[0] = ByteBuffer.allocate(5);
        byteBuffers[1] = ByteBuffer.allocate(3);

        //等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();

        int messageLength = 8;

        while (true){
            long byteRead = 0;
            while (byteRead < messageLength){
                long read = socketChannel.read(byteBuffers);
                //累计读取的字节数
                byteRead += read;
                System.out.println("byteRead="+byteRead);
                //当前的这个buffer的position 和 limit 输出
                Arrays.stream(byteBuffers).map(byteBuffer -> "position="+byteBuffer.position()
                +",limit="+byteBuffer.limit()).forEach(System.out::println);
            }
            //将所有的buffer反转
            Arrays.asList(byteBuffers).forEach(Buffer::flip);

            long byteWrite = 0;
            while (byteWrite < messageLength){
                long write = socketChannel.write(byteBuffers);
                byteWrite += write;

            }
            //将所有的buffer复位
            Arrays.asList(byteBuffers).forEach(Buffer::clear);

            System.out.println("byteRead ="+byteRead);
            System.out.println("byteWrite ="+byteWrite);
            System.out.println("messageLength ="+messageLength);
        }

    }
}

总结

  1. ByteBuffer 支持类型化的put和get ,put 放入的是什么数据类型,get就应该使用相应的数据类型来取出,否则可能有BufferUnderflowException 异常。


  2. 可以将一个普通Buffer 转成只读Buffer
  3. Nio 还提供了 MappedByteBuffer,可以让文件直接在内存(堆外内存)中进行修改,而如何同步到文件由NIO来完成。


  4. 前面我们将的读写 *** 作,都是通过一个buffer完成的,NIO还支持通过多个Buffer完成读写 *** 作,即Scattering 和 Gatering。


Channel(通道) 基本介绍

NIO 通道 类似于流,但有些区别如下:

  • 通道可以同时进行读写,而流只能读写或者只写
  • 通道可以实现异步读取数据
  • 通道可以从缓冲读数据,也可以写数据到缓冲
  1. BIO中的stream 是单向的,例如 FileInputStream 对象 只能进行读取数据的 *** 作,而NIO中的通道(Channel)是双向的,可以读 *** 作,也可以写 *** 作。


  2. Channel 在NIO 中是一个接口
  3. 常用的Channel 类有: FileChannel,SocketChannel,ServerSocketChannel,DatagramChannel
  4. FileChannel 用于文件读写 *** 作,DatagramChannel用于 UDP的数据读写 *** 作,ServerSocketChannel和SocketChannel用于TCP的读写 *** 作。


FileChannel

FileChannel,创建文件,写入内容 *** 作简单流程示意图:

读 *** 作代码示例一:

public class NIOFileChannel{
    public static void main(String[] agrs){
        //文件内容
        String str = "hello world";
        //创建一个文件输入流
        FileOutputStream fileOutputStream = new FileOutputStream("d:\file.txt");
        //得到一个文件管道
        FileChannel channel = fileOutputStream.getChannel();
        //创建一个缓冲区
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        //将字符串放入缓冲
        allocate.put(str.getBytes());
        //反转
        allocate.flip();
        //写入到管道里面去
        channel.write(allocate);
        //关闭流
        fileOutputStream.close();
    }
}

FileChannel,读取内容 *** 作示意图:

写 *** 作代码示例一:

public class NIOFileChannel2{
    public static void main(String[] agrs){
        //创建文件
        File file = new File("d:\file.txt");
		//得到文件输出流
        FileInputStream fileInputStream = new FileInputStream(file);
		//得到文件管道
        FileChannel channel = fileInputStream.getChannel();
		//得到缓存区
        ByteBuffer allocate = ByteBuffer.allocate((int) file.length());
        //读取内容到缓存中
        channel.read(allocate);
        //输出到控制台
        System.out.println(new String(allocate.array()));
        //关闭流
        fileInputStream.close();
    }
}

读写

public class NioFileChannelDemo3 {
    public static void main(String[] args) throws IOException {
        //创建一个文件输入流
        FileInputStream fileInputStream = new FileInputStream("d:\file.txt");
        FileChannel fileInputStreamChannel = fileInputStream.getChannel();

        //创建一个文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream("d:\file2.txt");
        FileChannel fileOutputStreamChannel = fileOutputStream.getChannel();

        //创建一个缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(512);

        //循环读取文件信息 输出文件信息
        while(true){
            //重置缓冲区
            byteBuffer.clear();
            //管道读取数据到缓冲区
            int read = fileInputStreamChannel.read(byteBuffer);
            if(read == -1){
                break;
            }
            //反转
            byteBuffer.flip();
            fileOutputStreamChannel.write(byteBuffer);
        }
        //关闭流
        fileInputStream.close();
        fileOutputStream.close();
    }
}
ServerSocketChannel

ServerSocketChannel ,在服务器端监听新的客户端 Socket连接

  • 得到ServerSocketChannel 通道
public static ServerSocketChannel open() throws IOException {....}
  • 设置服务器端口
public final ServerSocketChannel bind(SocketAddress local)throws IOException{....}
  • 设置非阻塞模式和阻塞模式,取值false表示采用阻塞模式
public final SelectableChannel configureBlocking(boolean block){....}
  • 接受一个连接,返回代表这个连接的通道的对象
public abstract SocketChannel accept() throws IOException;
  • 注册一个选择器并设置监听事件
 public final SelectionKey register(Selector sel, int ops, Object att)throws ClosedChannelException{....}
SocketChannel

SocketChannel,在网络IO通道,具体负责进行读写 *** 作,NIO把缓冲区的数据写入通道,或者把通道的数据读到缓冲区

  • 得到SocketChannel通道
public static SocketChannel open() throws IOException {....}
  • 设置非阻塞模式和阻塞模式,取值false表示采用阻塞模式
public final SelectableChannel configureBlocking(boolean block){....}
  • 连接服务器
public abstract boolean connect(SocketAddress remote) throws IOException;
  • 如果上面的方法失败,接下来就要通过该方法连接服务器
public abstract boolean finishConnect() throws IOException;
  • 往通道写数据
public abstract int write(ByteBuffer src) throws IOException;
  • 往通道读数据
public abstract int read(ByteBuffer dst) throws IOException;
  • 注册一个选择器并设置监听事件
 public final SelectionKey register(Selector sel, int ops, Object att)throws ClosedChannelException{....}
  • 关闭
 public final void close() throws IOException {{....}
Selector(选择器) 基本介绍

Java的NIO ,用非阻塞的IO的方式,可以用一个线程,处理多个的客户端连接,就会使用到Selector(选择器)。



Selector 能够检测多个注册的通道上是否有事件发生(多个Channel以事件的方式可以注册到同一个Selector),如果有事件发生,便获取事件然后针对每个事件进行相应的处理,这样就可以只用一个单线程去管理多个通道,也就是管理多个连接和请求。



只有在连接真正有读写事件发生时,才会进行读写,就大大地减少了系统的开销,并且不必为每个连接都创建一个线程,不用去维护多个线程。



避免了多线程之间的上下文切换导致的开销。


Selector特点
  1. Netty的IO线程NIOEventLoop 聚合了 Selector (选择器也叫多路复用器),可以同时并发处理成百上千个客户端连接。


  2. 当线程从某客户端Socket通道进行读写数据时,若没有数据可用时,该线程可以进行其他任务。


  3. 线程通常将非阻塞IO的空闲时间用于在其他通道上执行IO *** 作,所以单独的线程可以管理多个输入和输出通道
  4. 由于读写 *** 作都是非阻塞的,这就可以充分提升IO线程的运行效率,避免由于频率I/O阻塞导致的线程挂起
  5. 一个I/O 线程可以并发处理N个客户端连接和读写 *** 作,这从根本上解决了传统同步阻塞I/O 连接 线程模型,架构的性能,d性伸缩能力和可靠性都得到了极大的提升

常用api

  • 得到一个选择器的对象
public static Selector open() throws IOException {
        return SelectorProvider.provider().openSelector();
 }
  • 监控所有的注册的通道,当其有IO *** 作可以进行,将对应的SelectionKey 加入到内部集合中并返回,参数用来设置超时时间
public abstract int select(long timeout);
  • 从内部集合中得到所有的SelectionKey
public abstract Set<SelectionKey> selectedKeys();
  • 阻塞
selector.select()
  • 阻塞1000毫秒
selector.select(1000)
  • 唤醒selector
selector.wakeup()
  • 不阻塞,立马返还
selector.selectNow()
SelectionKey

表示 Selector 和网络通道的注册关系,共四种

源码228行,SelectionKey.class, 下面四个属性

  • 有新的网络连接可以 accept ,值为16
public static final int OP_ACCEPT = 1 << 4;
  • 代表连接已经建立,值为8
 public static final int OP_CONNECT = 1 << 3;
  • 代表读 *** 作,值为1
public static final int OP_READ = 1 << 0;
  • 代表写 *** 作 ,值为4
public static final int OP_WRITE = 1 << 2;

相关方法

  • 得到与之关联的Selector对象
public abstract Selector selector();
  • 得到与之关联的通道
public abstract SelectableChannel channel();
  • 得到与之关联的共享数据
public final Object attach(Object ob) {....}
  • 设置或改变监听事件
public abstract SelectionKey interestOps(int ops);
  • 是否可以接收
public final boolean isAcceptable() {....}
  • 是否可以读
public final boolean isReadable() {....}
  • 是否可以写
public final boolean isWritable() {....}
客户端代码示例
 package com.kelecc.nio;

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

/**
 * 功能描述: NIO 服务端 Demo
 *
 * @Author keLe
 */
public class NioClientDemo {
    public static void main(String[] args) throws IOException {
        SocketChannel socketChannel = SocketChannel.open();

        socketChannel.configureBlocking(false);

        InetSocketAddress inetSocketAddress = new InetSocketAddress(7000);
        //连接服务器,判断客户端是否连接成功
        if(!socketChannel.connect(inetSocketAddress)){

            while (!socketChannel.finishConnect()){
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他工作");
            }
        }
        //连接成功
        String str = "hello world ";

        ByteBuffer byteBuffer = ByteBuffer.wrap(str.getBytes());
        //写入到通道里面
        socketChannel.write(byteBuffer);
        System.in.read();

    }
}

服务端代码示例
package com.kelecc.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;
import java.util.Set;

/**
 * 功能描述: NIO 服务器端 Demo
 *
 * @Author keLe
 */
public class NioServerDemo {
    public static void main(String[] args) throws IOException {
        //创建 ServerSocketChannel -> ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();

        //Selector对象
        Selector selector = Selector.open();

        //创建一个socket对象,绑定地址 ,服务器 监听7000端口
        serverSocketChannel.socket().bind(new InetSocketAddress(7000));
        //设置为非阻塞
        serverSocketChannel.configureBlocking(false);
        //注册
        serverSocketChannel.register(selector, SelectionKey.OP_CONNECT);

        //循环等待客户端连接
        while(true){
            //没有事件发生
            if(selector.select(1000) == 0){
                System.out.println("服务器等待了1s");
                continue;
            }

            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                //如果是 OP_CONNECT ,有新的客户端连接进来
                if(key.isAcceptable()){
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功,生成一个SocketChannel"+socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                //如果是 OP_READ,说明是读取事件
                if(key.isReadable()){
                    //通过key 获取到对应channel
                    SocketChannel channel = (SocketChannel)key.channel();
                    //获取当前通道,channel 关联的buffer
                    ByteBuffer byteBuffer = (ByteBuffer)key.attachment();
                    System.out.println("from 客户端" +new String(byteBuffer.array()));

                }
                //手动从集合中移到当前的selectionKey,防止重复 *** 作
                iterator.remove();
            }
        }
    }
}

NIO非阻塞网络编程

原理分析图

  1. 当客户端连接时,会通过 ServerSocketChannel 得到 SocketChannel
  2. 将 SocketChannel 注册到 Selector 上
  3. 注册后返回一个 SelectionKey,会和该 Selector 关联 (集合)
  4. Selector 进行监听 (用 select 方法),返回有事件发生的通道的个数
  5. 进一步得到各个 SelectionKey (有事件发生)
  6. 再通过 SelectionKey 反向获取 SocketChannel
  7. 可以通过得到的 Channel 完成业务处理
简易群聊服务器端代码示例
package com.kelecc.nio.gruopchat;

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

/**
 * 功能描述: TODO 方法描述
 *
 * @Author keLe
 */
public class GroupChatServer {

    private Selector selector;

    private ServerSocketChannel listenChannel;

    private static  final  int PORT = 6666;

    public GroupChatServer(){
        try {
            //得到一个选择器
            selector = Selector.open();
            //服务器的通道
            listenChannel = ServerSocketChannel.open();
            //设置监听端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞
            listenChannel.configureBlocking(false);
            //注册到选择器
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    /**
     * 功能描述:监听
     * @Author keLe
     * @return void
     */
    public void listen() {
        try {
            while (true){
                int count = selector.select();
                //有事件出现
                if(count>0){
                    Set<SelectionKey> selectionKeys = selector.selectedKeys();
                    Iterator<SelectionKey> iterator = selectionKeys.iterator();
                    while (iterator.hasNext()){
                        SelectionKey key = iterator.next();
                        //连接事件
                        if(key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            //设置非阻塞
                            sc.configureBlocking(false);
                            sc.register(selector, SelectionKey.OP_READ);
                            System.out.println(sc.getRemoteAddress() + "上线");
                        }
                        //有读取事件
                        if(key.isReadable()){
                            readData(key);
                        }
                        iterator.remove();
                    }
                }else{
                    System.out.println("等待。








"); } } }catch (IOException e){ e.printStackTrace(); } } /** * 功能描述: 读取数据 * @Author keLe * @param key * @return void */ public void readData(SelectionKey key){ SocketChannel channel = null; try { channel = (SocketChannel)key.channel(); ByteBuffer byteBuffer = ByteBuffer.allocate(1024); int count = channel.read(byteBuffer); if(count > 0){ String msg = new String(byteBuffer.array()); System.out.println("from 客户端 " + msg); sendInfoToOtherClients(msg,channel); } } catch (IOException e) { try { System.out.println(channel.getRemoteAddress()+" 离线了。








"); //取消注册 key.cancel(); //关闭通道 channel.close(); }catch (IOException e1){ e.printStackTrace(); } } } //转发消息给其他通道,排除自己通道 private void sendInfoToOtherClients(String msg,SocketChannel self){ System.out.println("服务器,消息转发中"); for (SelectionKey key : selector.keys()) { Channel targetChannel = key.channel(); if(targetChannel instanceof SocketChannel && targetChannel != self){ SocketChannel dest = (SocketChannel) targetChannel; ByteBuffer byteBuffer = ByteBuffer.wrap(msg.getBytes()); try { //写入 dest.write(byteBuffer); } catch (IOException e) { e.printStackTrace(); } } } } public static void main(String[] args) throws IOException { GroupChatServer groupChatServer = new GroupChatServer(); groupChatServer.listen(); } }

简易群聊客服端代码示例
package com.kelecc.nio.gruopchat;

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.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;

/**
 * 功能描述: 群聊客户端
 *
 * @Author keLe
 */
public class GroupChatClient {

    private static final String HOST = "127.0.0.1";

    private static final int POST = 6666;

    private Selector selector;

    private  SocketChannel socketChannel;

    private String userName;

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //绑定地址和端口
        socketChannel = socketChannel.open(new InetSocketAddress(HOST,POST));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //注册
        socketChannel.register(selector, SelectionKey.OP_READ);
        userName = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(userName+"  is ok ....");
    }

    /**
     * 功能描述: 向服务器发送消息
     * @Author keLe
     * @param  info  消息体
     * @return void
     */
    public void sendInfo(String info) throws IOException {
        info = userName + "说:"+info;
        socketChannel.write(ByteBuffer.wrap(info.getBytes()));
    }

    public  void readInfo() throws IOException {
        int select = selector.select(2000);
        if(select>0){
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            Iterator<SelectionKey> iterator = selectionKeys.iterator();
            while (iterator.hasNext()){
                SelectionKey next = iterator.next();
                if(next.isReadable()){
                    SocketChannel sc  =  (SocketChannel)next.channel();
                    ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
                    sc.read(byteBuffer);
                    System.out.println(new String(byteBuffer.array()).trim());
                }
                iterator.remove();
            }
        }
    }

    public static void main(String[] args) throws Exception {
        GroupChatClient groupChatClient = new GroupChatClient();
        new Thread(){
            @Override
            public void run() {
                while (true){
                    try {
                        groupChatClient.readInfo();
                        Thread.currentThread().sleep(3000);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            groupChatClient.sendInfo(s);
        }
    }
}

结果



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/langs/562558.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-04-01
下一篇 2022-04-01

发表评论

登录后才能评论

评论列表(0条)

保存