java网络编程——NIO架构

2023-10-26

目录

1.什么是NIO

2.NIO结构

3.基于NIO下的聊天系统实现

4.Netty


1.什么是NIO

NIO:java non-blocking IO,同步非阻塞IO。

BIO是阻塞IO,即每一个事件都需要分配一个进程给他,如果客户端没有连接上,则一直阻塞等待。

而NIO,异步 I/O 是一种没有阻塞地读写数据的方法:该架构下我们可以注册对特定 I/O 事件诸如数据可读、新连接到来等等,而在发生这样感兴趣的事件时,系统将会告诉您,而不用一直等待。

打个比方:

五个人(请求)写作业,BIO架构下是五个老师(五个进程)看着写,学生直接在书上写(内存读写)。
NIO架构下则是一个老师(进程)看着写,要求学生先写在本子上(buffer,缓冲区),并且一直问助教(selector),写好的(事件就绪)交上来!

2.NIO结构

NIO主要有三大核心部分:Channel(通道),Buffer(缓冲区), Selector。

Channel和IO中的Stream(流)类似。只不过Stream是单向的,channel是双向的,既可以用来进行读操作,又可以用来进行写操作。

Buffer:NIO中的缓冲区,本质上是一个可读取的内存块。当向buffer写入数据时,buffer会记录下写了多少数据。一旦要读取数据,需要通过flip()方法将Buffer从写模式切换到读模式,读取之前写入到buffer的所有数据。

NIO和java中普通IO最大的区别是数据打包和传输方式。传统IO基于字节流和字符流进行操作,而NIO基于Channel和Buffer(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。

如上图所示:客户端/服务端将需要传输的数据存入到buffer缓冲区中,再通过java流获取对应的channel,然后使用channel写入/读取缓冲区中的数据,输出到对应的目标(文件/字节流)中。

selector:要使用Selector, 得向Selector注册Channel,然后调用它的select()方法进行监听:这个方法会一直阻塞到至少一个注册的通道有事件就绪;当事件就绪,会把对应的selectionKey(用于关联channel,每一个类型的事件对应一个selectionKey,可以帮助获得对应的channel进行后续操作)加入到内部集合,并返回;一旦这个方法返回,线程就可以处理这些事件。

注:select()方法是阻塞的,select(1000)方法阻塞1000毫秒;selectNow()方法是非阻塞的

当客户端发起一次请求事件过后,NIO架构的响应过程如下图所示:

首先,服务端会获得一个ServerSocketChannel并向selector注册,即可等待客户端连接。

客户端向服务端发起请求,selector通过select()方法监听到事件发生(如客户端读事件),分配线程处理该事件;服务端将事件类型对应的selectionKey返回,然后通过key获得处理的channel,通过channel.read()方法将数据写入buffer,并返回至客户端;客户端从buffer中读到需要的数据,请求结束。

Selector(选择区)用于监听多个通道的事件(比如:连接打开,数据到达),只有当 通道 真正有读写事件发生时,才会进行读写,大大减少系统开销,避免了多线程之间的上下文切换。这使得一个I/O线程可以并发处理多个客户端连接和读写操作,极大提升了性能。 

3.基于NIO下的聊天系统实现

基于以上架构,我们可以根据NIO结构,编写一个聊天系统:

(1)服务端:

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

public class ChatServer {
    private ServerSocketChannel serverSocketChannel;
    private Selector selector;
    public static final int port = 8080;

    public ChatServer(){
        try {
            //获取ServerSocketChannel供客户端连接,并开放端口
            serverSocketChannel = ServerSocketChannel.open();
            serverSocketChannel.socket().bind(new InetSocketAddress(port));
            serverSocketChannel.configureBlocking(false);
            //得到Selector,并注册channel
            selector = Selector.open();
            serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
            System.out.println("服务器就绪");
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void listen(){
        try {
            while (true){
                //阻塞2秒
                int count = selector.select(2000);

                if (count>0){
                    //有事件需要处理
                    Iterator<SelectionKey> keyIterator = selector.selectedKeys().iterator();
                    while (keyIterator.hasNext()){
                        SelectionKey key = keyIterator.next();
                        //客户端连接事件,为客户端生成SocketChannel
                        if (key.isAcceptable()){
                            SocketChannel socketChannel = serverSocketChannel.accept();
                            //非阻塞channel才能进行注册
                            socketChannel.configureBlocking(false);
                            //注册,绑定事件读,并为该channel关联buffer
                            socketChannel.register(selector,SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                            System.out.println("客户端:"+socketChannel.getRemoteAddress()+" 成功连接");
                        }
                        //读取事件
                        if (key.isReadable()){
                            readMessage(key);
                        }

                        //删除已处理key,避免重复操作
                        keyIterator.remove();
                    }
                }else {
                    continue;
                }
            }
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    //从客户端读取消息
    private void readMessage(SelectionKey key){
        SocketChannel channel = null;
        try {
            //通过key反向获取channel
            channel = (SocketChannel) key.channel();
            //获取该channel关联buffer
            ByteBuffer buffer = ByteBuffer.allocate(1024);
            //从buffer中读取数据
            int read = channel.read(buffer);
            if (read>0){
                String msg = new String(buffer.array()).trim();
                //转发消息(排除自己)
                transformMessage(msg,channel);
            }

        }catch (IOException e){
            try {
                System.out.println(channel.getRemoteAddress()+"下线");
                //取消注册
                key.cancel();
                //关闭通道
                channel.close();
            }catch (Exception exception){
                exception.printStackTrace();
            }
        }
    }
    //转发消息给其他客户端
    public void transformMessage(String msg, SocketChannel self) throws IOException {
        System.out.println("服务器转发消息");
        //遍历所有注册到selector的channel,进行转发
        for (SelectionKey key:selector.keys()){
            Channel targetChannel = key.channel();
            //排除自己
            if (targetChannel instanceof SocketChannel && targetChannel!=self){
                //转发消息
                SocketChannel dest = (SocketChannel) targetChannel;
                ByteBuffer buffer = ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8));
                dest.write(buffer);
            }

        }
    }

    public static void main(String[] args) {
        ChatServer chatServer = new ChatServer();
        chatServer.listen();
    }
}
  1. 建立ServerSocketChannel,开放端口,并设置为非阻塞。      
  2. 获取一个selector,并将channel注册进去,绑定触发事件及对应的SelectionKey
  3. 等待客户端连接。
  4. 当select()方法监听到事件,获取事件的selectionKey集合;遍历集合,处理事件。(连接事件则创建socketChannel连接;读事件则读取buffer中消息,并转发至其他客户端)

注:只有阻塞模式下,channel才可以向selector注册serverSocketChannel.accept()获取的SocketChannel也需要设置;server端先生成一个ServerSocketChannel并注册后,客户端才可以用SocketChannel对其进行连接; 

(2)客户端:

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.nio.charset.StandardCharsets;
import java.util.Iterator;
import java.util.Scanner;

public class ChatClient implements Runnable{
    private SocketChannel socketChannel;
    private final String host = "127.0.0.1";
    private final int port = 8080;
    private Selector selector;
    private String username;

    public ChatClient(){
        try {
            socketChannel=SocketChannel.open(new InetSocketAddress(host, port));
            socketChannel.configureBlocking(false);
            selector=Selector.open();
            socketChannel.register(selector, SelectionKey.OP_READ);
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println("客户端就绪");
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    //发送消息
    public void sendMsg(String msg){
        msg = username + ":" + msg;
        try {
            socketChannel.write(ByteBuffer.wrap(msg.getBytes(StandardCharsets.UTF_8)));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //读取回复消息
    public void readMsg(){
        try {
            int select = selector.select();
            Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
            while (iterator.hasNext()){
                SelectionKey key = iterator.next();
                if (key.isReadable()){
                    SocketChannel channel = (SocketChannel) key.channel();
                    ByteBuffer buffer = ByteBuffer.allocate(1024);
                    channel.read(buffer);

                    String str = new String(buffer.array());
                    System.out.println(str.trim());
                }
                iterator.remove();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {
        while (true){
            this.readMsg();
            //每隔1秒监听一次
            try {
                Thread.sleep(1000);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    public static void main(String[] args) {
        ChatClient chatClient = new ChatClient();
        //启动线程读取
        new Thread(chatClient).start();
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String str = scanner.nextLine();
            chatClient.sendMsg(str);
        }

    }
}
  1. 获取scocketServer连接服务端,设置非阻塞模式。
  2. 连接服务端。
  3. 发起事件:发送消息,将消息写入channel中。
  4. 读取服务器转发的其他客户单消息。

(3)运行效果:

服务端:

 客户端1:

 客户端2:

 客户端3:

4.Netty

Netty是 一个异步事件驱动的网络应用程序框架(即基于NIO架构),用于快速开发可维护的高性能协议服务器和客户端。

为什么会有Netty?

  • 1)NIO的类库和API繁杂,使用起来比较麻烦;
  • 2)开发工作量和难度大,面临例如断连重连、半包读写、失败缓存等问题;
  • 3)使用原生NIO编程需要掌握Reactor模型、多线程编程等额外技能,要求较高;
  • 4)java原生NIO存在一定的bug,可能会影响NIO编程。

而Netty就是基于Reactor多线程模型 对 JDK 自带的 NIO 的 API 进行了良好的封装,解决了上述问题。且Netty拥有高性能、 吞吐量更高,延迟更低,减少资源消耗,最小化不必要的内存复制等优点。

其核心在于 可拓展事件驱动模型、全局交互API、零拷贝。

Netty快速使用,其使用形式类似于NIO架构,也是分为服务端、客户端:

(1)服务端:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;

public class NettyServer {
    public static void main(String[] args) {
        //定义线程组:BossEventLoop(负责连接) , WorkerEventLoop(负责业务读写)
        EventLoopGroup bossEventLoop = new NioEventLoopGroup(1);
        EventLoopGroup workerEventLoop = new NioEventLoopGroup();

        try {
            // 1. ServerBootstrap:启动器,负责组装netty组件,启动服务器
            new ServerBootstrap()
                    // 2.存入线程组
                    .group(bossEventLoop,workerEventLoop)
                    // 3.选择服务器的ServerSocketChannel实现
                    .channel(NioServerSocketChannel.class)
                    // 4. worker(child) , 决定了worker能执行什么操作(handler)
                    .childHandler(
                            // 5. channel 代表和客户端进行读写的通道 Initializer:初始化器,负责添加别的handler
                            new ChannelInitializer<NioSocketChannel>() {
                                @Override
                                protected void initChannel(NioSocketChannel ch) throws Exception {
                                    // 6. 添加具体handler
                                    ch.pipeline().addLast(new StringDecoder()); //将 ByteBuf 转为字符串
                                    ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {   //自定义handler
                                        @Override   //读事件
                                        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                            System.out.println(msg);
                                        }
                                    });
                                }
                            })
                    .bind(8080);

        }catch (Exception e){
            System.out.println("客户端断开连接");
        }

    }
}

(2)客户端:

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;

import java.net.InetSocketAddress;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {

        try {
            // 1.启动类
            new Bootstrap()
                    // 2.添加EventLoop
                    .group(new NioEventLoopGroup())
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new StringEncoder());
                        }
                    })
                    .connect(new InetSocketAddress("localhost",8080))
                    .sync()
                    .channel()
                    //发送数据
                    .writeAndFlush("hello world");
        }catch (Exception e){
            System.out.println("服务器异常");
        }

    }
}

上述代码实现了服务端创建ServerSocketChannel,客户端连接服务端并写入消息,服务端成功读取的功能。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java网络编程——NIO架构 的相关文章

随机推荐

  • 暑期必须要学习的52个Python+OpenCV实战项目

    点击上方 小白学视觉 选择加 星标 或 置顶 重磅干货 第一时间送达 有个粉丝前几天问我 本人小白一枚 看了很多深度学习 机器学习以及图像处理等视频和书之后 理论有一些长进 但是实际运用能力不足 从反面也是由于理论认识不足所致 所以想问问有
  • 完整的vuejs + django 前后端分离项目实践(登录,注册,权限控制,可视化)

    完整的vuejs django 前后端分离项目实践 登录 注册 权限控制 可视化 vuejs是一个流行的前端框架 django是一个python非常流行的web框架 在某期的作业中 需要基于它两实现一个前端后分离 并且拥有权限管理的系统 声
  • 哈夫曼编码

    哈夫曼编码 Huffman Coding 又称霍夫曼编码 是一种编码方式 哈夫曼编码是可变字长编码 VLC 的一种 Huffman于1952年提出一种编码方法 该方法完全依据字符出现概率来构造异字头的平均长度最短的码字 有时称之为最佳编码
  • sqlmap配置

    1 我们先去sqlmap官网上下载sqlmap的压缩包 2 把解压后的压缩包放在python27的安装路径下 这个路径指的是 然后配置环境变量 新增一个D python2 7 17 sqlmap sqlmapproject sqlmap 1
  • 感谢导师每次组会的锻炼,让我收获今年最想去的一个offer

    题解 名单中出现过的人 a input tuple1 tuple Tom Tony Allen Cydin Lucy Anna print tu 神策校园招聘来啦 你想要跟老板们扁平化相处吗 你想每天吃不完的水果零食饮品不限量吗 毕业第一份
  • 笔记-flowable工作流开启节点自动跳过

    flowable工作流开启节点自动跳过 笔记 开始 准备工作 1 flowable支持流程跳转的功能 在流程图绘画的时候可以设置一个表达式让节点自动跳过 2 在流程开启时需要设置参数 笔记 开始 我们在使用工作流时经常会遇到需要自动跳过节点
  • HTML

    HTML 下拉框和文本域 文件域 1 下拉框 在平时我们填问卷或者冲浪的时候做筛选的时候都会遇到下拉框 html写一个下拉框的方式是使用select标签 name和id是默认属性
  • Android问题集(五)——解决提示:The method **() is undefined for the type ***()

    使用情景 在非Activity子类方法中 有时想要调用Activity类特有的方法 系统会提示无该方法The method is undefined 思路 将Activity的父类Context作为方法参数 通过context调用该方法 例
  • Fckeditor常见漏洞的挖掘与利用整理汇总

    查看编辑器版本 FCKeditor whatsnew html 2 Version 2 2 版本 Apache linux 环境下在上传文件后面加个 突破 测试通过 3 Version lt 2 4 2 For php 在处理PHP 上传的
  • Django 快速搭建博客 第十一节(文章阅读量统计,自动生成文章摘要)

    这一节主要做一些修补工作 一个是 文章阅读量的统计 另一个是自动生成文章摘要内容 1 文章阅读量的统计 1 文章阅读量的统计 我们需要在model下的Post类中新加入一个views 字段用来统计文章被阅读的数量 blog models p
  • 是否二叉搜索树

    习题4 3 是否二叉搜索树 25分 本题要求实现函数 判断给定二叉树是否二叉搜索树 函数接口定义 bool IsBST BinTree T 其中BinTree结构定义如下 typedef struct TNode Position type
  • Go语言函数

    http www jb51 net article 56831 htm Go语言中的函数有系统函数和自定义函数 1 系统函数 系统函数就是Go语言自带的函数 系统函数一般根据功能封装在不同的包内 比如Print Printf Println
  • 微信聊天记录导出工具WeChatExporter开源啦!

    2019年08月21日更新 距离第一次发布软件已经有了许多新功能和稳定性上的提升 本文的一些内容已经过时 欢迎直接到GitHub上看ReadMe https github com tsycnh WeChatExporter 之前曾经写过一个
  • 消息队列 - RabbitMQ - 拓展

    1 Message 状态 Message 在投递时 如果当前 Queue 没有 Message 且有 Consumer 已经订阅了这个 Queue 那么该 Message 会直接发送给 Consumer 不会经过 Queue 存储 Mess
  • 在 Substance Painter中自定义Shader

    为什么要学习在Substance Painter中自定义Shader 答 需要实现引擎与Substance Painter中的渲染效果一致 材质的配置也一致 所见即所得 基础概述 首先在着色器设置这里 我们可以查看当前渲染使用的着色器 如果
  • ETL笔记——第五章 数据清洗与校验(数据检验)

    一 数据一致性处理 通过Kettle工具 使用弱一致性对数据表Personnel Information中的数据进行一致性处理 即利用数据表Personnel Information中的字段GENDER中的值训练出一个健康值预测模型 用于将
  • Android学习之Activity源码的理解(一)

    一 Activity为Android系统中四大组件之一 是Android程序的呈现层 并通过界面与用户进行交互 因此理解Activity源码是有必要的 二 之前我写过一篇文章 http blog csdn net u012561176 ar
  • scrapy的工作流程

    scrapy的工作流程如下图所示 整个工作流程 爬虫中起始的url构造成request对象 并传递给调度器 引擎从调度器中获取到request对象 然后交给下载器 由下载器来获取到页面源代码 并封装成response对象 并回馈给引擎 引擎
  • 测试开发-面试题目整理

    1 java的三大特性 封装 继承 多态 2 python的三大特性 封装 继承 多态 3 多态是怎么实现的 4 重载和重写的区别是什么 5 java的八大数据类型 6 花旗金融算法 java的冒泡法怎么实现的 几层for循环 7 得物面试
  • java网络编程——NIO架构

    目录 1 什么是NIO 2 NIO结构 3 基于NIO下的聊天系统实现 4 Netty 1 什么是NIO NIO java non blocking IO 同步非阻塞IO BIO是阻塞IO 即每一个事件都需要分配一个进程给他 如果客户端没有