网络编程之NIO

原文链接

基本介绍

1、NIO(non-blocking IO)是JDK提供的新API,从JDK1.4开始,Java提供了一系列改进的输入/输出新特性,被统称为NIO(即 New IO), 是同步非阻塞
2、NIO 有三大核心部分:Channel(通道)、Buffer(缓冲区)、Selector(选择器)
3、 NIO 是面向缓冲区,或者面向块编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使用它可以提供非阻塞式的高伸缩性网络
4、NIO的非阻塞模式,一个线程从某通道发送请求或者读取数据时,这个线程仅仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而不是阻塞线程,所以直至数据可以读取之前,该线程可以继续做其他的事情。非阻塞谢也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情

NIO和BIO的比较

1、BIO以流的方式处理数据,而NIO以块的方式处理数据,块I/O的效率比流I/O高很多
2、BIO是阻塞的,NIO是非阻塞的
3、BIO基于字节流和字符流进行操作,而NIO基于Channel(管道)和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。Selecter(选择器)用于监听多个通道的事件(连接请求,数据到达等),因此使用单个线程就可以监听多个客户端通道

NIO三大核心原理

在这里插入图片描述
1、每个Channel 都会对应一个Buffer
2、Selector对应一个线程,一个线程对应多个Channel(连接)
3、该图反映了有三个Channel注册到Selector
4、程序切换到哪个Channel是由事件决定的,Event就是一个重要的概念
5、Selector会根据不同的事件,在各个通道上切换
6、Buffer就是一个内存块,底层是一个数组
7、数据的读取写入是通过Buffer,BIO中要么是输入流,或者是输出流不能双向,但是NIO的Buffer是可以读也可以写,需要flip 方法切换,Channel是双向的,可以返回底层操作系统的情况,比如Linux,底层的操作系统通道就是双向的

Buffer(缓冲区)

介绍

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

在这里插入图片描述

继承关系
1、Buffer是一个顶级父类,它是一个抽象类,类的层级关系图
在这里插入图片描述

2、Buffer类定义了4个属性

名称含义
capacity容量,即可以容纳的最大数据量;在缓冲区创建时被设定且不能改变
limit表示缓冲区的当前终点,不能与缓冲区超过极限的位置进行读写操作,limit可以修改
position位置,下一个要被读或写的元素的索引,每次读写缓冲区数据时都会改变,为下次读写做准备
mark标记

3、Buffer定义的方法

public abstract class Buffer {
    //JDK1.4引入的api
    public final int capacity()//返回此缓冲区的容量
    public final int position()//返回此缓冲区的位置
    public final Buffer position(int newPosition)//返回此缓冲区的位置
    public final int limit()//返回此缓冲区的限制
    public final Buffer limit(int newLimit)//设置此缓冲区的限制
    public final Buffer mark()//在此缓冲区的位置设置标记
    public final Buffer reset()//在此缓冲区的位置重置为以前标记的位置
    public final Buffer clear()//清除此缓冲区,即将各个标记恢复到初始状态,但是数据并没有真正擦除
    public final Buffer flip()//反转此缓冲区
    public final Buffer rewind()//重绕此缓冲区
    public final int remaining()//返回当前位置与极限位置之间的元素数
    public final boolean hasRemaining()//告知在当前位置和极限位置之间是否有元素
    public abstract boolean isReadOnly()//告知此缓冲区是否为只读缓冲区

    //JDK1.6时引入的api
    public abstract boolean hasArray();//告知此缓冲区是否具有可访问的底层实现数组
    public abstract Object array();//返回此缓冲区的底层实现数组
    public abstract int arrayOffset();//返回此缓冲区的底层实现数组中第一个缓冲区元素的偏移量
    public abstract boolean isDirect();//告知此缓冲区是否为直接缓冲区
}

4、 ByteBuffer
对于Java中的基本数据类型(boolean 除外),都有一个Buffer 类型与之对应,最常用的自然是ByteBuffer类(二进制数据),该类的主要方法如下:

public abstract class ByteBuffer {
    //缓冲区创建相关api
    public static ByteBuffer allocateDirect(int capacity)//创建直接缓冲区的初始容量
    public static ByteBuffer allocate(int capacity)//创建缓冲区的初始容量
    public static ByteBuffer wrap(byte[] array)//把一个数组放到缓冲区中使用
    public static ByteBuffer wrap(byte[] array,int offset,int length)//构造初始化位置offset和上界length的缓冲区
    //缓存区存取相关api
    public abstract byte get();//从当前位置position上get, get之后, position会自动+1
    public abstract byte get(int index);//从绝对位置get
    public abstract ByteBuffer put(byte b);//从当前位置上添加, put之后, position会自动+1
    public abstract ByteBuffer put(int index,byte b);//从绝对位置上put
}

Channel(通道)

1、 InputStream其实就是一个用来读取文件的通道。只不过InputStream是一个单向的通道,只能用来读取数据。而NIO中的Channel是一个双向的通道,不仅能读取数据,而且还能写数据。
2、常用的Channel类有:FileChannel(文件读写)、DatagramChannel(UDP数据读写)、ServerSocketChannel(服务端TCP数据读写)、SocketChannel(TCP数据读写)。

FileChannel类常用方法

public abstract class FileChannel {
    public int read(FileChannel dst)//从通道读取数据并放到缓冲区中
    public int write(FileChannel src)//把缓冲区的数据写道通道中
    public long transferForm(ReadableByteChannel src,long position,long count)//从目标通道中复制数据到当前通道
    public long transferTo(long position, long count, WritableByteChannel target)//把数据从当前通道复制给目标通道
}

通道应用实例

1、使用ByteBuffer和Channel 将 “hello,world” 写入到file01.txt

package com.tk.netty.nio;

import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 使用ByteBuffer和Channel 将 “hello,world” 写入到file01.txt
 *
 * @author taoke
 * @date 2022/5/7
 */
public class NioFileChannel01 {

    public static void main(String[] args) throws Exception {
        String str = "hello,world";
        //创建一个输出流
        FileOutputStream outputStream = new FileOutputStream("file01.txt");
        //通过输出流获取通道,真实类型是FileChannelImpl
        FileChannel channel = outputStream.getChannel();
        //创建一个缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        //将数据放入缓冲区
        buffer.put(str.getBytes());
        //调用flip方法
        buffer.flip();
        //将byteBuffer写入通道中
        channel.write(buffer);
        outputStream.close();
    }
}

运行结果
在这里插入图片描述

2、将file01.txt中的数据读入到程序,并显示在控制台

package com.tk.netty.nio;

import java.io.File;
import java.io.FileInputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 将file01.txt中的数据读入到程序,并显示在控制台
 *
 * @author taoke
 * @date 2022/5/7
 */
public class NioFileChannel02 {

    public static void main(String[] args) throws Exception {
        //创建文件输入流
        File file = new File("file01.txt");
        FileInputStream fileInputStream = new FileInputStream(file);
        //通过fileInputStream获取通道,真实类型是FileChannelImpl
        FileChannel channel = fileInputStream.getChannel();
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate((int) file.length());
        //将通道的数据读取到缓冲区
        channel.read(buffer);
        //将byteBuffer 的字节数据转换为字符串
        System.out.println(new String(buffer.array()));
        fileInputStream.close();
    }
}

执行结果
在这里插入图片描述
3、使用通道Channel 将文件“file01.txt”拷贝,文件名为“file02.txt”

package com.tk.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 将文件“file01.txt”拷贝,文件名为“file02.txt”
 *
 * @author taoke
 * @date 2022/5/7
 */
public class NioFileChannel03 {

    public static void main(String[] args) throws Exception {
        //创建文件输入流
        FileInputStream fileInputStream = new FileInputStream("file01.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("file02.txt");
        //通过文件流流获取通道,真实类型是FileChannelImpl
        FileChannel channel01 = fileInputStream.getChannel();
        FileChannel channel02 = fileOutputStream.getChannel();
        //创建缓冲区
        ByteBuffer buffer = ByteBuffer.allocate(1024);
        while (true) {
            //清空buffer
            buffer.clear();
            //将通道的数据读取到缓冲区
            int read = channel01.read(buffer);
            if (read == -1) {
                break;
            }
            //将buffer中的数据写入到file02,txt
            buffer.flip();
            channel02.write(buffer);
        }
        //关闭资源
        fileInputStream.close();
        fileOutputStream.close();
    }
}

执行结果
在这里插入图片描述

4、使用通道Channel和方法transferTo 将文件file01.txt拷贝file02.txt

package com.tk.netty.nio;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.channels.FileChannel;

/**
 * 使用通道Channel和方法transferTo 将文件file01.txt拷贝file02.txt
 *
 * @author taoke
 * @date 2022/5/7
 */
public class NioFileChannel04 {

    public static void main(String[] args) throws Exception {
        //创建文件输入流
        FileInputStream fileInputStream = new FileInputStream("file01.txt");
        FileOutputStream fileOutputStream = new FileOutputStream("file02.txt");
        //通过文件流流获取通道,真实类型是FileChannelImpl
        FileChannel sourceChannel = fileInputStream.getChannel();
        FileChannel targetChannel = fileOutputStream.getChannel();
        sourceChannel.transferTo(0, sourceChannel.size(), targetChannel);
        //关闭资源
        sourceChannel.close();
        targetChannel.close();
        fileInputStream.close();
        fileOutputStream.close();
    }
}

运行结果
在这里插入图片描述

Buffer和Channel注意事项和细节

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

package com.tk.netty.nio;

import java.nio.ByteBuffer;

/**
 * ByteBuffer 支持类型化的put和get
 *
 * @author taoke
 * @date 2022/5/7
 */
public class NioByteBufferPutGet {

    public static void main(String[] args) {
        ByteBuffer buffer = ByteBuffer.allocate(64);
        buffer.putInt(1);
        buffer.putLong(2L);
        buffer.putChar('陶');
        buffer.putShort((short) 3);
        buffer.flip();
        System.out.println(buffer.getInt());
        System.out.println(buffer.getLong());
        System.out.println(buffer.getChar());
        System.out.println(buffer.getShort());
    }
}

运行结果
在这里插入图片描述
2、将一个普通Buffer转为只读Buffer

package com.tk.netty.nio;

import java.nio.ByteBuffer;

/**
 * 将一个普通Buffer转为只读Buffer
 *
 * @author taoke
 * @date 2022/5/7
 */
public class ReadOnlyBuffer {

    public static void main(String[] args) {
        ByteBuffer byteBuffer = ByteBuffer.allocate(64);
        for (int i = 0; i < 10; i++) {
            byteBuffer.put((byte) i);
        }
        //读取
        byteBuffer.flip();
        ByteBuffer readOnlyBuffer = byteBuffer.asReadOnlyBuffer();
        while (readOnlyBuffer.hasRemaining()) {
            System.out.println(readOnlyBuffer.get());
        }
//        readOnlyBuffer.put((byte) 10); ReadOnlyBufferException
    }

}

运行结果
在这里插入图片描述
3、NIO提供了MappedByteBuffer,可以让文件直接在内存(堆外内存)中进行修改,而如何同步到文件由NIO来完成

package com.tk.netty.nio;

import java.io.RandomAccessFile;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

/**
 * 文件直接在内存(堆外内存)中进行修改
 *
 * @author taoke
 * @date 2022/5/7
 */
public class MappedByteBufferDemo {

    public static void main(String[] args) throws Exception {
        RandomAccessFile randomAccessFile = new RandomAccessFile("file01.txt", "rw");
        //获取对应的通道
        FileChannel channel = randomAccessFile.getChannel();
        /*
         * 参数1:FileChannel.MapMode.READ_WRITE 使用读写模式
         * 参数2:0,可以直接修改的起始位置
         * 参数3:5,映射到内存的大小(不是索引位置),即将file01.txt的多少个字节映射到内存
         * 可以直接修改的范围就是0-5
         * 实际类型 DirectByteBuffer
         */
        MappedByteBuffer mappedByteBuffer = channel.map(FileChannel.MapMode.READ_WRITE, 0, randomAccessFile.length());
        mappedByteBuffer.put(0, (byte) 'H');
        mappedByteBuffer.put(6, (byte) 'W');
        randomAccessFile.close();
        System.out.println("修改成功!");
    }
}

运行结果
因为直接在堆外内存中修改,所以编译器中的数据不是最新的,在磁盘打开发现已经更新成功。
在这里插入图片描述
4、NIO还支持多个Buffer(即Buffer数组)完成读写操作,即Scattering和Gathering

package com.tk.netty.nio;

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分散聚集操作
 *
 * @author taoke
 * @date 2022/5/7
 */
public class ScatteringAndGathering {

    public static void main(String[] args) throws Exception {
        //使用ServerSocketChannel和SocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        InetSocketAddress socketAddress = new InetSocketAddress(7000);
        //绑定端口到socket,并启动
        serverSocketChannel.socket().bind(socketAddress);

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

        //等待客户端连接
        SocketChannel socketChannel = serverSocketChannel.accept();
        //假定从客户端接收8个字节
        int messageLength = 8;
        //循环的读取
        while (true) {
            int byteRead = 0;
            while (byteRead < messageLength) {
                long l = socketChannel.read(byteBuffers);
                byteRead += l;
                //累计读取的字节数
                System.out.println("byteRead=" + byteRead);
                //使用流打印,看看当前的这个buffer的position和limit
                Arrays.stream(byteBuffers).map(buffer -> "position=" + buffer.position() + ", limit=" + buffer.limit())
                        .forEach(System.out::println);
            }
            //将所有的buffer进行flip
            Arrays.asList(byteBuffers).forEach(Buffer::flip);
            //将数据读出显示到客户端
            long byteWrite = 0;
            while (byteWrite < messageLength) {
                long l = socketChannel.write(byteBuffers);
                byteWrite += l;
            }
            //将所有的buffer进行clear
            Arrays.asList(byteBuffers).forEach(Buffer::clear);
            System.out.println("byteRead=" + byteRead + " byteWrite=" + byteWrite + ", messageLength" + messageLength);
        }
    }
}

运行结果
telnet 连接服务端发送 “123456”共6个字节数据
在这里插入图片描述
服务端收到6个字节数据,第一个buffer有5个,第二个buffer有1个
在这里插入图片描述
telnet 连接服务端发送 “12345678”共8个字节数据
在这里插入图片描述
服务端收到8个字节数据,第一个buffer有5个,第二个buffer有3个,发送和写入的数据都是8个字节
在这里插入图片描述

Selector(选择器)

1、NIO的选择器可以使用一个线程,处理多个客户端的连接
2、选择器能够检测多个通道是否有事件发生(多个通道以事件的方式可以注册到同一个选择器),当有事件发生时,选择器可以获取事件并进行处理。这样就可以只用一个线程去管理多个通道,也就是管理多个连接和请求。
3、只有在连接/通道 真正有事件读写发生时,才会进行读写,就大大减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多个线程,避免了多线程之间的上下文切换导致的开销

Selector类常用方法

public abstract class Selector implements Closeable {
    public static Selector open()//得到一个选择器对象
    //监控所有注册的通道,当其中有IO操作可以进行时,将对应的SelectionKey加入到内部集合中并返回,参数可以设置超时时间
    public int select(long timeout)
    public abstract Set<SelectionKey> selectedKeys();//从内部集合中得到所有的selectionKey
}

selector相关方法说明

selector.select()//阻塞
selector.select(1000)//阻塞1000ms, 在1000ms之后返回
selector.selectNow()//不阻塞,立刻返回
selector.wakeup()//唤醒selector

Selector、SelectionKey、ServerSocketChannel、SocketChannel之间的关系
1、当客户端连接时,会通过ServerSocketChannel得到SocketChannel
2、Selector进行监听select方法,返回有事件发生的通道的个数
3、将socketChannel注册到Seletor上,register(Selector s,int ops),一个selector上可以注册多个SocketChannel
4、注册后返回一SelectionKey,会和Selector关联(集合)
5、进一步得到各个SelectionKey(有事件发生)
6、再通过SelectionKey反向获取SocketChannel,方法channel()
7、通过得到的channel,完成业务处理
在这里插入图片描述

NIO网络编程小案例

采用非阻塞的方式实现服务端和客户端之间的简单通讯

服务端

package com.tk.netty.nio;

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服务端
 *
 * @author taoke
 * @date 2022/5/9
 */
public class NIOServer {

    public static void main(String[] args) throws Exception {
        //创建ServerSocketChannel
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        //得到一个Selector对象
        Selector selector = Selector.open();
        //绑定端口6666,在服务端监听
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        //设置为为非阻塞
        serverSocketChannel.configureBlocking(false);
        //把serverSocketChannel注册到selector,关心事件为OP_ACCEPT(连接事件)
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        //循环等待客户端连接
        while (true) {
            //这里等待1s,如果没有事件发生就返回
            if (selector.select(1000) == 0) {//没有事件发生
                System.out.println("服务器等待了1s, 无连接");
                continue;
            }
            //返回关注事件的集合
            Set<SelectionKey> selectionKeys = selector.selectedKeys();
            //遍历 Set<SelectionKey>,使用迭代器
            Iterator<SelectionKey> keyIterator = selectionKeys.iterator();
            while (keyIterator.hasNext()) {
                //获取SelectionKey
                SelectionKey key = keyIterator.next();
                //根据key对应的通道发生的事件做相应的处理
                if (key.isAcceptable()) {//如果是OP_ACCEPT,有新的客户端连接
                    //该客户端生成一个SocketChannel
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端连接成功,生成了一个socketChannel=" + socketChannel.hashCode());
                    //将socketChannel设置为非阻塞
                    socketChannel.configureBlocking(false);
                    //将socketChannel注册到selector,关注事件为OP_READ,同时给socketChannel关联一个buffer
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                }
                if (key.isReadable()) {//如果是OP_READABLE,有新的客户端连接
                    //通过key反向获取到对应channel
                    SocketChannel channel = (SocketChannel) key.channel();
                    //获取到该channel关联的buffer
                    ByteBuffer buffer = (ByteBuffer) key.attachment();
                    channel.read(buffer);
                    buffer.flip();
                    System.out.println("from 客户端" + new String(buffer.array(), 0, buffer.limit()));
                }
                //手动从集合中移动当前的selectionKey,防止重复操作
                keyIterator.remove();
            }
        }

    }
}

客户端

package com.tk.netty.nio;

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

/**
 * NIO 客户端
 *
 * @author taoke
 * @date 2022/5/9
 */
public class NIOClient {

    public static void main(String[] args) throws Exception {
        //得到一个网络通道
        SocketChannel socketChannel = SocketChannel.open();
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //提供服务器端的ip和端口
        InetSocketAddress inetSocketAddress = new InetSocketAddress("127.0.0.1", 6666);
        //连接服务器
        if (!socketChannel.connect(inetSocketAddress)) {
            while (!socketChannel.finishConnect()) {
                System.out.println("因为连接需要时间,客户端不会阻塞,可以做其他工作");
            }
        }
        //如果连接成功,就发送数据
        String str = "hello,world";
        //wrap a byte array into a buffer
        ByteBuffer buffer = ByteBuffer.wrap(str.getBytes());
        //发送数据,将buffer数据写入channel
        socketChannel.write(buffer);
        System.in.read();
    }
}

运行结果
服务端启动,非阻塞等待客户端连接
在这里插入图片描述
客户端成功连接服务端
在这里插入图片描述

SelectionKey

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

OP_READ:代表读操作,值为1
OP_WRITE:代表写操作,值为4
OP_ACCEPT:有新的网络连接可以accept,值为16
OP_CONNECT:代表连接已经建立,值为8

源码中:
public static final int OP_READ=1<<0
public static final int OP_WRITE=1<<2
public static final int OP_ACCEPT=1<<4
public static final int OP_CONNECT=1<<3

相关方法

public abstract class SelectionKey {
    public abstract java.nio.channels.Selector selector();//得到与之关联的Selector对象
    public abstract SelectableChannel channel();//得到与之关联的通道
    public final Object attachment()//得到与之关联的共享数据
    public abstract SelectionKey interestOps(int ops);
    public final boolean isAcceptable()//是否可以accept
    public final boolean isReadable()//是否可以读
    public final boolean isWriteable()//是否可以写
}

ServerSocketChannel

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

相关方法

public abstract class ServerSocketChannel extends AbstractSelectableChannel implements NetworkChannel {
    public static ServerSocketChannel open();//得到一个ServerSocketChannel通道
    public final ServerSocketChannel bind(SocketAddress local);//设置服务器端端口号
    public final SelectableChannel configureBlocking(boolean block);//设置阻塞或非阻塞模式,取值false表示采用非阻塞模式
    public SocketChannel accept();//接收一个连接,返回代表这个连接的通道对象
    public final SelectionKey register(Selector sel,int ops);//注册一个选择器并设置监听事件
}

SocketChannel

SocketChannel负责具体进行读写操作,NIO把缓冲区的数据写入通道,或者把通道的数据读到缓冲区。

public abstract class ServerSocketChannel extends AbstractSelectableChannel implements
        ByteChannel, ScatteringByteChannel, GatheringByteChannel, NetworkChannel {
    public static SocketChannel open();//得到一个SocketChannel通道
    public final SelectableChannel configureBlocking(boolean block);//设置阻塞或者非阻塞模式,取值false表示采用非阻塞模式
    public boolean connect(SocketAddress remore);//连接服务器
    public boolean finishConnect();//如果上面的方法连接失败,接下来就要通过该方法完成连接操作
    public int write(ByteBuffer src);//往通道里面写数据
    public int read(ByteBuffer dst);//从通道里面读数据
    public final SelectionKey register(Selector sel,int ops,Object att);//注册一个选择器并设置监听事件,最后一个参数可以设置共享数据
    public final void close();//关闭通道
}

网络编程应用实例-群聊系统

实例要求:
1、编写一个NIO群聊系统,实现服务器端和客户端之间的数据简单通讯(非阻塞)
2、实现多人群聊
3、服务器端可以检测用户上线、离线,并实现消息转发功能
4、客户端可以通过channel无阻塞发送消息给其他所有用户,同时可以接收其他用户发送的消息(服务器转发)

服务器端

package com.tk.netty.nio.groupchat;

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

/**
 * 群聊服务器端
 *
 * @author taoke
 * @date 2022/5/10
 */
public class GroupChatServer {
    private Selector selector;
    private ServerSocketChannel listenChannel;
    private static final int PORT = 6667;

    public static void main(String[] args) {
        GroupChatServer server = new GroupChatServer();
        server.listen();
    }

    /**
     * 初始化工作
     */
    public GroupChatServer() {
        try {
            //得到选择器
            selector = Selector.open();
            //ServerSocketChannel
            listenChannel = ServerSocketChannel.open();
            //绑定端口
            listenChannel.socket().bind(new InetSocketAddress(PORT));
            //设置非阻塞模式
            listenChannel.configureBlocking(false);
            //将该listenChannel注册到selector
            listenChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听
     */
    public void listen() {
        try {
            while (true) {
                int count = selector.select();
                if (count > 0) {//有事件处理
                    //遍历得到selectionKey集合
                    Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                    while (iterator.hasNext()) {
                        //取出selectionKey
                        //监听到accept
                        SelectionKey key = iterator.next();
                        if (key.isAcceptable()) {
                            SocketChannel sc = listenChannel.accept();
                            sc.configureBlocking(false);
                            //将该sc注册到selector
                            sc.register(selector, SelectionKey.OP_READ);
                            //提示
                            System.out.println(sc.getRemoteAddress() + " 上线");
                        }
                        if (key.isReadable()) {//通道发送read事件,即通道是可读的状态
                            //处理读
                            readData(key);
                        }
                        //当前key删除,防止重复处理
                        iterator.remove();
                    }
                } else {
                    System.out.println("等待。。。");
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取客户端消息
     *
     * @param key SelectionKey
     */
    private void readData(SelectionKey key) {
        //取到关联的channel
        SocketChannel channel = null;
        try {
            //得到channel
            channel = (SocketChannel) key.channel();
            //创建buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            int count = channel.read(buffer);
            if (count > 0) {
                //把缓冲区的数据转成字符串
                String msg = new String(buffer.array(),0,buffer.position());
                //输出该消息
                System.out.println("from 客户端:" + msg);
                //向其他的客户端转发消息(去掉自己)
                sendInfoToOtherClients(msg, channel);
            }
        } catch (Exception e) {
            try {
                if (channel != null) {
                    System.out.println(channel.getRemoteAddress() + "离线了");
                    key.cancel();
                    //关闭通道
                    channel.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
            e.printStackTrace();
        }
    }

	/**
     * 转发消息给其他客户端
     *
     * @param msg  消息
     * @param self 当前通道
     */
    private void sendInfoToOtherClients(String msg, SocketChannel self) {
        try {
            System.out.println("服务器转发消息中。。。");
            //遍历所有注册到selector上的SocketChannel,并排除self
            for (SelectionKey key : selector.keys()) {
                //通过key取出对应的SocketChannel
                Channel targetChannel = key.channel();
                //排除自己
                if (targetChannel instanceof SocketChannel && targetChannel != self) {
                    //转型
                    SocketChannel dest = (SocketChannel) targetChannel;
                    //将msg存储到buffer
                    ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes());
                    //将buffer写入到通道
                    dest.write(buffer);
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

客户端

package com.tk.netty.nio.groupchat;

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.Scanner;

/**
 * 群聊客户端
 *
 * @author taoke
 * @date 2022/5/10
 */
public class GroupChatClient {

    private final String HOST = "127.0.0.1";
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public static void main(String[] args) throws Exception {
        GroupChatClient client = new GroupChatClient();
        new Thread(() -> {
            try {
                client.readInfo();
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();
        //发送数据给服务端a
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            client.sendInfo(s);
        }
    }

    public GroupChatClient() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open(new InetSocketAddress(HOST, PORT));
        //设置非阻塞
        socketChannel.configureBlocking(false);
        //将channel注册到selector
        socketChannel.register(selector, SelectionKey.OP_READ);
        //得到username
        username = socketChannel.getLocalAddress().toString().substring(1);
        System.out.println(username + " is ok!");
    }

    public void sendInfo(String info) {
        info = username + " 说:" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 读取服务端信息
     */
    public void readInfo() {
        try {
            int readChannels = selector.select();
            if (readChannels > 0) {
                for (SelectionKey key : selector.selectedKeys()) {
                    if (key.isReadable()) {
                        //得到相关的通道
                        SocketChannel sc = (SocketChannel) key.channel();
                        //得到一个Buffer
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        //读取
                        sc.read(buffer);
                        //把读到的缓冲区的数据转成字符串
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
            } else {
                System.out.println("没有可用的通道");
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

运行结果
1、启动服务端,客户端0,客户端1
在这里插入图片描述
2、客户端0发送消息
在这里插入图片描述
3、服务端收到并转发客户端0的消息,客户端1收到群发的消息
在这里插入图片描述
在这里插入图片描述
4、客户端0离线,服务端收到提示
在这里插入图片描述

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值