NIO入门并通过NIO实现多人聊天功能

1 篇文章 0 订阅

I/O 型基本说明

  1. I/O 型简单的理解就是用什么样的通行数据的发送和接收,很大程度上决定序通信的
  2. Java共支持3种网络编程模/IO模式:BIONIOAIO
  3. 步阻塞服务器实现模式为一个连接一个线程,即客户端有连接请求时服务器端就需要启动一个线程进行处理,如果这个连接不做任何事情会造成不必要的线程开销,可以通过线程池机制改(实现多个客户连接服务器)。BIO方式适用于连接数目比较小且固定的架构,这种方式对服务器资源要求比较高,并发局限于应用中,JDK1.4以前的唯一选择,程序简单易理解
  4. 同步非阻塞,服务器实现模式为一个线程处理多个请求(连接),即客户端发送的连接请求都会注册到多路复用器上,多路复用器轮询到连接有I/O请求就进行处理
  5. 异步非阻塞AIO 引入异步通道的概念,采用了 Proactor 模式,简化了程序编写,有效的请求才启动线程,它的特点是先由操作系统完成后才通知服务端程序启动线程去处理,一般适用于连接数较多且连接时间较长的应用
Java NIO 基本介绍
 
1) Java NIO 全称 java non-blocking IO ,是指 JDK 提供的新 API 。从 JDK1.4 开始, Java 提供 了一 系列改进的输入 / 输出的新特性,被统称为 NIO( New IO ) ,是 同步非阻塞
 
2) NIO 相关类都被放在 java.nio 包及子包下,并且对原 java.io 包中的很多类进行改写
 
3) NIO 有三大核心部分: Channel( 通道 ) Buffer( 缓冲区 ) , Selector( 选择器 )
 
4) NIO 是 面 冲区 ,或者面向 编程的。数据读取到一个它稍后处理的缓冲区,需要时可在缓冲区中前后移动,这就增加了处理过程中的灵活性,使 用它可以提供 非阻塞 式的高伸缩性网
 
5) Java NIO 的非阻塞模式,使一个线程从某通 道发 送请 求或者读 取数据,但是它仅能得到目前可用的数据,如果目前没有数据可用时,就什么都不会获取,而 不是保持线程阻塞 ,所以直至数据变的可以读取之前,该线程可以继续做其他的事情。 非阻塞写也是如此,一个线程请求写入一些数据到某通道,但不需要等待它完全写入,这个线程同时可以去做别的事情
 
6) 俗理解: NIO 是可以做到用一个线程来处理多个操作的。假设有 10000 个请求过来 , 根据实际情况,可以分配 50 或者 100 个线程来处理。不像之前的阻塞 IO 那样,非得分配 10000
 
7) HTTP2.0 使用了多路复用的技术,做到同一个连接并发处理多个请求,而且并发请求的数量比 HTTP1.1 大了好几个数量级。
 
 
 

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

 

public class BasicBuffer {
    public static void main(String[] args) {

        //举例说明Buffer 的使用 (简单说明)
        //创建一个Buffer, 大小为 5, 即可以存放5个int
        IntBuffer intBuffer = IntBuffer.allocate(5);

        //向buffer 存放数据
//        intBuffer.put(10);
//        intBuffer.put(11);
//        intBuffer.put(12);
//        intBuffer.put(13);
//        intBuffer.put(14);
        for(int i = 0; i < intBuffer.capacity(); i++) {
            intBuffer.put( i * 2);
        }

        //如何从buffer读取数据
        //将buffer转换,读写切换(!!!)
        /*
        public final Buffer flip() {
        limit = position; //读数据不能超过5
        position = 0;
        mark = -1;
        return this;
    }
         */
        intBuffer.flip();
        intBuffer.position(1);//1,2
        System.out.println(intBuffer.get());
        intBuffer.limit(3);
        while (intBuffer.hasRemaining()) {
            System.out.println(intBuffer.get());
        }
    }

    public void testBuffer() {
        IntBuffer buffer = IntBuffer.allocate(5);
        for (int i = 0; i < buffer.capacity(); i ++) {
            buffer.put(i * 2);
        }
        buffer.flip();
        if(buffer.hasRemaining()) {
            buffer.get();
        }

    }
}

Buffer的类型

Java NIO 有以下Buffer类型他们都继承了Buffer抽象类 其本身也是抽象类

  • ByteBuffer
  • MappedByteBuffer
  • CharBuffer
  • DoubleBuffer
  • FloatBuffer
  • IntBuffer
  • LongBuffer
  • ShortBuffer

Buffer的重要属性:

public abstract class Buffer {

    /**
     * The characteristics of Spliterators that traverse and split elements
     * maintained in Buffers.
     */
    static final int SPLITERATOR_CHARACTERISTICS =
        Spliterator.SIZED | Spliterator.SUBSIZED | Spliterator.ORDERED;

    // Invariants: mark <= position <= limit <= capacity
    private int mark = -1;
    private int position = 0;
    private int limit;
    private int capacity;

capacity

作为一个内存块,Buffer有一个固定的大小值,也叫“capacity”.你只能往里写capacity个byte、long,char等类型。一旦Buffer满了,需要将其清空(通过读数据或者清除数据)才能继续写数据往里写数据。

position

当你写数据到Buffer中时,position表示当前的位置。初始的position值为0.当一个byte、long等数据写到Buffer后, position会向前移动到下一个可插入数据的Buffer单元。position最大可为capacity – 1.

当读取数据时,也是从某个特定位置读。当将Buffer从写模式切换到读模式,position会被重置为0. 当从Buffer的position处读取数据时,position向前移动到下一个可读的位置。

limit

在写模式下,Buffer的limit表示你最多能往Buffer里写多少数据。 写模式下,limit等于Buffer的capacity。

当切换Buffer到读模式时, limit表示你最多能读到多少数据。因此,当切换Buffer到读模式时,limit会被设置成写模式下的position值。换句话说,你能读到之前写入的所有数据(limit被设置成已写数据的数量,这个值在写模式下就是position)

Buffer相关Api

//初始化buffer
IntBuffer intBuffer = IntBuffer.allocate(5);
//flip方法将Buffer从写模式切换到读模式。调用flip()方法会将position设回0,并将limit设置成之前position的值。

    public final Buffer flip() {
        limit = position;
        position = 0;
        mark = -1;
        return this;
    }

public void testBuffer() {
        IntBuffer buffer = IntBuffer.allocate(5);
        for (int i = 0; i < buffer.capacity(); i ++) {
//将值写入buffer中
            buffer.put(i * 2);
        }
//将写模式转化为读模式
        buffer.flip();
//判断buffer中是否还有数据
        if(buffer.hasRemaining()) {

//获取buffer中的数据会导致position后移
            buffer.get();
        }

    }
/**
*clear方法将buffer的position恢复到初始值,但并没有将数据清空,再次写入数据的时候只是将原本的值覆盖
*/
public final Buffer clear() {
        position = 0;
        limit = capacity;
        mark = -1;
        return this;
    }
(Channel) 
       1) NIO 的通道类似于流,但有些区别如下
道可以同时进行读写,而流只能读或者只能
道可以实现异步读写数
道可以从缓冲读数据,也可以写数据到缓冲
2) BIO 中的 stream 是单 向的 ,例如 FileInputStream 对象只能进行读取数据的操作,而 NIO 中的通道 (Channel) 是双向的 ,可以读 操作,也可 以写 操作
3) Channel NIO 中是一个接口
public interface Channel extends Closeable{}
4) 用的 Channel 类有: FileChannel DatagramChannel ServerSocketChannel SocketChannel ServerSocketChanne 类似 ServerSocket , SocketChannel Socket】
5) FileChannel 用于文件的数据读写 DatagramChannel 用于 UDP 的数据读写, ServerSocketChannel SocketChannel 用于 TCP 的数 据读写。
 

FileChannel

FileChannel要用来对本地文件进行 IO 作,常见的方法有

1) public int read(ByteBuffer dst) ,从通道读取数据并放到缓冲区
2) public int write(ByteBuffer src) ,把缓冲区的数据写到通道
3) public long transferFrom(ReadableByteChannel src, long position, long count) ,从目标通 道中 复制数据到当前通
4) public long transferTo(long position, long count, WritableByteChannel target) ,把数据从 当前 通道复制给目标通道

 

public class NIOFileChannel01 {
    public static void main(String[] args) throws Exception{

        String str = "hello";
        //创建一个输出流->channel
        FileOutputStream fileOutputStream = new FileOutputStream("d:\\file01.txt");

        //通过 fileOutputStream 获取 对应的 FileChannel
        //这个 fileChannel 真实 类型是  FileChannelImpl
        FileChannel fileChannel = fileOutputStream.getChannel();

//        MappedByteBuffer map = fileChannel.map(FileChannel.MapMode.READ_WRITE, 0, 1024);
//        map.put(str.getBytes());
//        map.flip();
//        fileChannel.write(map);

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

        //将 str 放入 byteBuffer
        byteBuffer.put(str.getBytes());


        //对byteBuffer 进行flip
        byteBuffer.flip();

        //将byteBuffer 数据写入到 fileChannel
        fileChannel.write(byteBuffer);
        fileOutputStream.close();

    }
}

//FileChannel 可以通过map方法创建BUFFER
public abstract MappedByteBuffer map(MapMode mode,long position, long size)
throws IOException;


 

selector基本介绍

1) Java NIO ,用非阻塞的 IO 式。可 以用一个线程,处 多个 的客户 端连 接,就会使用到 Selector ( 选择器 )
 
2) Selector 够检测多个注册的通道上是否有事件发 ( 注意 : 多个 Channel 以事件的方式可以注册到同一个 Selector) 如果有事件发生,便 获取 事件然后针对每个事件进行相应的处理。这样就可以只用一个单线程去管理多个通道, 也就 是管理多个连 接和请求。 示意图
3) 在 连接 / 通道 真 正有读写事件发生时,才 会进 行读写 ,就 大大地减少了系统开销,并且不必为每个连接都创建一个线程,不用去维护多 线程
4) 免了多线程之间的上下文切换导致的开
 
 

 NIO模型

Selector Channel Buffer 系图(简单版)

图的说明:

1) 每个 channel 都会对应一个 Buffer
2) Selector 对应一个线程, 个线程对应多个 channel( 连接 )
3) 该图反应了有 channel 注册到 该 selector // 程序
4) 序切换到 channel 是有事件决定的 , Event 就是一个重要的概念
5) Selector 会根据不同的事件,在各个通道上切换
6) Buffer 就是一个内存块 , 层是有一个数组
7) 据的读取写入是通过 Buffer, 这个和 BIO , BIO 中要么是输入流,或者是
出流 , 不能双向,但是 NIO Buffer 是可以读也可以写 , 需要 flip 方法

           channel 是双向的, 可以返回底层操作系统的情况, 比如Linux 层的操作系
           通道就是双向的.

 

NIO实现多人聊天

//服务端代码
public class Server {

    private ServerSocketChannel servSocketChannel;
    private Selector selector;

    /**
     * 初始化服务器
     * */
    public Server(){

        try {
            servSocketChannel = ServerSocketChannel.open();
            servSocketChannel.socket().bind(new InetSocketAddress(7000));
            selector = Selector.open();
            //开启非阻塞模式
            servSocketChannel.configureBlocking(false);
            //注册serverSocketChannel
            servSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 监听连接
     * */
    public void listen()  {
        while (true) {
            Iterator<SelectionKey> keyIterator = null;
            try {
                //这里我们等待1秒,如果没有事件发生, 返回
                if(selector.select(1000) == 0) { //没有事件发生

                    continue;
                }
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                keyIterator = selectionKeys.iterator();
                if(keyIterator.hasNext()) {
                    SelectionKey key = keyIterator.next();
                    //客户端连接
                    if(key.isAcceptable()) {
                        SocketChannel socketChannel = servSocketChannel.accept();
                        socketChannel.configureBlocking(false);
                        socketChannel.register(selector, SelectionKey.OP_READ);
                        System.out.println(socketChannel.getRemoteAddress() + "上线");
                    }
                    //读已就绪
                    if(key.isReadable()) {
                        readData(key);
                    }else{
                        System.out.println("等待处理");
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //当前的key 删除,防止重复处理
            keyIterator.remove();
        }
    }
    public void readData(SelectionKey selectionKey) {
        SocketChannel channel = (SocketChannel)selectionKey.channel();
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        try {
            int read = channel.read(byteBuffer);
            while (read > 0) {
                String msg = new String(byteBuffer.array());
                System.out.println(msg);
                //转发
                sendInfoToOtherClients(msg, channel);
                byteBuffer.clear();
                read = channel.read(byteBuffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void sendInfoToOtherClients(String msg, SocketChannel channel) {
        Set<SelectionKey> keys = selector.keys();
        for (SelectionKey key : keys) {
            SelectableChannel targetChannel = key.channel();
            if(targetChannel instanceof SocketChannel && targetChannel != channel) {
                SocketChannel socketChannel = (SocketChannel) targetChannel;
                ByteBuffer wrap = ByteBuffer.wrap(msg.getBytes());
                try {
                    socketChannel.write(wrap);
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.listen();
    }
}
//客户端代码
public class Client {
    private SocketChannel socketChannel;
    private final String IP = "127.0.0.1";
    private Selector selector;
    private final int port = 7000;
    private String username;

    public Client() {
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress(IP, port));
            selector = Selector.open();
            socketChannel.configureBlocking(false);
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + " is ok...");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //读取从服务器端回复的消息
    public void readInfo() {

        try {

            int readChannels = selector.select();
            if(readChannels > 0) {//有可以用的通道

                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {

                    SelectionKey key = iterator.next();
                    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());
                    }
                }
                iterator.remove(); //删除当前的selectionKey, 防止重复操作
            } else {
                //System.out.println("没有可以用的通道...");

            }

        }catch (Exception e) {
            e.printStackTrace();
        }
    }

    //向服务器发送消息
    public void sendInfo(String info) {

        info = username + " 说:" + info;

        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws Exception {

        //启动我们客户端
        Client chatClient = new Client();

        //启动一个线程, 每个3秒,读取从服务器发送数据
        new Thread() {
            public void run() {

                while (true) {
                    chatClient.readInfo();
                    try {
                        Thread.currentThread().sleep(3000);
                    }catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        //发送数据给服务器端
        Scanner scanner = new Scanner(System.in);

        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }

}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值