java网络编程——NIO架构

这篇具有很好参考价值的文章主要介绍了java网络编程——NIO架构。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

目录

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(缓冲区)进行操作,数据总是从通道读取到缓冲区中,或者从缓冲区写入到通道中。

java网络编程——NIO架构

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

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

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

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

java网络编程——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)运行效果:

服务端:

java网络编程——NIO架构

 客户端1:

java网络编程——NIO架构

 客户端2:

java网络编程——NIO架构

 客户端3:

java网络编程——NIO架构

4.Netty

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

为什么会有Netty?

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

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

java网络编程——NIO架构

其核心在于 可拓展事件驱动模型、全局交互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,客户端连接服务端并写入消息,服务端成功读取的功能。文章来源地址https://www.toymoban.com/news/detail-426297.html

到了这里,关于java网络编程——NIO架构的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包 赞助服务器费用

相关文章

  • Java网络编程----通过实现简易聊天工具来聊聊NIO

    前文我们说过了BIO,今天我们聊聊NIO。 NIO 是什么?NIO官方解释它为 New lO ,由于其特性我们也称之为,Non-Blocking IO。这是jdk1.4之后新增的一套IO标准。 为什么要用NIO呢? 我们再简单回顾下BIO: 阻塞式IO,原理很简单,其实就是多个端点与服务端进行通信时,每个客户端有一个

    2024年02月05日
    浏览(48)
  • NIO基础 - 网络编程

    non-blocking io 非阻塞 IO 1.1 Channel Buffer channel 有一点类似于 stream,它就是读写数据的 双向通道 ,可以从 channel 将数据读入 buffer,也可以将 buffer 的数据写入 channel,而之前的 stream 要么是输入,要么是输出,channel 比 stream 更为底层 常见的 Channel 有 FileChannel DatagramChannel SocketCh

    2024年02月02日
    浏览(27)
  • NIO-Selector 网络编程

    目录 一、阻塞 非阻塞 1、阻塞 2、非阻塞 二、selector 1、连接和读取 2、处理客户端断开 3、处理消息的边界 4、ByteBuffer大小分配 三、多线程优化 四、NIO vs BIO 1、stream vs channnel 2、IO模型 阻塞IO 非阻塞IO 多路复用 异步IO模型 服务器端的代码 然后创建客户端,直接连服务器端的

    2024年02月12日
    浏览(25)
  • 10.NIO 网络编程应用实例-群聊系统

    需求:进一步理解 NIO 非阻塞网络编程机制,实现多人群聊 编写一个 NIO 群聊系统,实现客户端与客户端的通信需求(非阻塞) 服务器端:可以监测用户上线,离线,并实现消息转发功能 客户端:通过 channel 可以无阻塞发送消息给其它所有客户端用户,同时可以接受其它客户端用

    2024年02月15日
    浏览(28)
  • 由浅入深Netty基础知识NIO网络编程

    阻塞模式下,相关方法都会导致线程暂停 ServerSocketChannel.accept 会在没有连接建立时让线程暂停 SocketChannel.read 会在没有数据可读时让线程暂停 阻塞的表现其实就是线程暂停了,暂停期间不会占用 cpu,但线程相当于闲置 单线程下,阻塞方法之间相互影响,几乎不能正常工作,

    2024年02月05日
    浏览(43)
  • Linux:概述 、安装 、文件与目录结构 、vim编辑器 、网络配置 、远程登录 、系统管理 、基础命令 、软件包管理 、克隆虚拟机 、shell编程

    2.1.1、Linux是什么? Linux是一个操作系统(OS) 所谓的操作系统就是直接用来操作计算机底层硬件的软件。 2.1.2、Linux的出现 官网: https://www.centos.org/ 进入官网进行下载 有很多的镜像,以阿里云的为例: 3.3.1、下载 官网: https://www.vmware.com/ 这是下载的企业版,30天试用期,可

    2024年02月05日
    浏览(48)
  • 【Netty专题】【网络编程】从OSI、TCP/IP网络模型开始到BIO、NIO(Netty前置知识)

    我是有点怕网络编程的,总有点【谈网色变】的感觉。为了让自己不再【谈网色变】,所以我想过系统学习一下,然后再做个笔记这样,加深一下理解。但是真要系统学习,其实还是要花费不少时间的,所以这里也只是简单的,尽可能地覆盖一下,梳理一些我认为比较迫切需

    2024年02月06日
    浏览(48)
  • 什么是网络编程?Java如何实现?三次握手和四次挥手?

    个人简介:Java领域新星创作者;阿里云技术博主、星级博主、专家博主;正在Java学习的路上摸爬滚打,记录学习的过程~ 个人主页:.29.的博客 学习社区:进去逛一逛~ 网络编程 : 网络编程,就是指在网络通信协议下,不同计算机运行的程序,进行的数据传输,即:计算机与

    2024年02月08日
    浏览(32)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包