网络编程-Netty-02 Netty核心功能及线程模型

【网络编程】一文搞定Netty,打造单机百万连接测试! 一文搞定Netty,打造单机百万连接测试! 阅读详情

1、Netty解决的痛点

  • NIO的类库和API复杂,需要对Selector、ServerSocketChannel、SocketChannel、ByteBuffer等做操作。
  • 针对客户端断线重连、网络闪断、线条处理、半包读写、网络拥塞、异常等分别处理。
  • Netty对JDK自带的API做了封装,能够解决上述问题。
  • Netty拥有高性能、高吞吐、低时延等优点。

2、Netty的使用场景

  • 分布式系统中,各节点间远程服务调用需要高性能的RPC框架。Netty作为优秀的异步高性能通信框架,往往作为基础通信组件。
    • 阿里分布式框架Dobbo进行节点通信,使用Netty进行进程间通信。
    • RocketMQ使用Netty作为基础通信组件
    • 华为分布式服务框架servicecomb的Edge Service的是基于Netty的vertx作为基础通信组件
  • 游戏行业,通过Netty作为高性能基础通信组件,提供TCP/UDP和http协议栈
  • 大数据领域,hadoop高性能通信和序列化Avro的RPC框架,默认采用Netty进行跨界点通信。

3、客户端、服务端demo

先跑demo后,了解基本功能,后看源码。

    <!--Netty-->
    <dependency>
      <groupId>io.netty</groupId>
      <artifactId>netty-all</artifactId>
      <version>4.1.73.Final</version>
    </dependency>

客户端:

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

public class NettyClient {
    public static void main(String[] args) throws InterruptedException {
        //客户端事件循环组 默认线程数为 cpu-core*2
        NioEventLoopGroup group = new NioEventLoopGroup(1);
        try {
            Bootstrap bootstrap = new Bootstrap();
            //设置bootstrap参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyClientHandler());
                        }
                    });
            System.out.println("netty client start...");
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9090);
            //启动客户端连接服务器
            cf.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyClientHandler extends ChannelInboundHandlerAdapter {

    /**
     * 建连完成
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ByteBuf buf = Unpooled.copiedBuffer("HelloServer".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(buf);
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("收到服务端的消息:" + buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("数据流读取完毕");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获异常"+cause);
    }
}

服务端:

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

public class NettyServer {
    public static void main(String[] args) throws InterruptedException {
        //创建管理连接的线程组
        EventLoopGroup bossGroup = new NioEventLoopGroup(2);
        //创建处理业务逻辑的线程组
        EventLoopGroup workerGroup = new NioEventLoopGroup(10);
        try {
            //创建服务器端的启动对象
            ServerBootstrap bootstrap = new ServerBootstrap();
            //配置启动参数(两个线程组)
            bootstrap.group(bossGroup,workerGroup)
                    //服务器通道的实现
                    .channel(NioServerSocketChannel.class)
                    //将瞬时无法处理的请求加入队列
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    });
            System.out.println("netty server start...");
            //启动服务器(绑定端口号) bind是异步操作 sync是等待异步绑定结果的同步操作
            ChannelFuture cf = bootstrap.bind(9090).sync();
            //等待服务器监听端口关闭,closeFuture是异步操作
            //通过sync同步等待通道关闭处理完毕,这里会阻塞等待通道关闭完成,内部调用的是Object.wait()方法
            cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

public class NettyServerHandler extends ChannelInboundHandlerAdapter {

    /**
     * 当客户端与服务端完成连接时出发
     *
     * @param ctx
     * @throws Exception
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        System.out.println("客户端连接通道建立完成");
    }

    /**
     * 读取客户端发送的数据
     *
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        ByteBuf buf = (ByteBuf) msg;
        System.out.println("收到客户端的消息:" + buf.toString(CharsetUtil.UTF_8));
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        System.out.println("数据读取完毕");
        ByteBuf buf = Unpooled.copiedBuffer("HelloClient".getBytes(CharsetUtil.UTF_8));
        ctx.writeAndFlush(buf);
    }

    /**
     * 异常捕获
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获异常"+cause);
    }
}

4、Netty线程模型理解

4.1Doug lea《Scalable IO in Java》中的可扩展的网络IO线程模型
  • Classic Service Designs 经典服务设计

    特点

    • 单线程处理请求
    • 每个请求经过读消息 —> 解码 —> 处理请求 —> 编码 —> 响应客户端数据
    • 阻塞式响应

    在这里插入图片描述

  • Basic Reactor Design 响应式事件驱动模型

    • 特点
    • 异步非阻塞响应(linux系统下基于epoll文件描述器中断响应)
    • 由acceptor对客户端连接进行响应
    • 再由dispatch对读写事件进行处理

    在这里插入图片描述

  • Using Multiple Reactors 多线程主从响应式事件驱动模型

    • 特点
    • mainReactor主负责连接
    • 连接后生成的channel注册到subReactor,再由subReactor分配worker threads线程,对编解码和处理
      在这里插入图片描述
4.2 Netty的线程模型(网络版)

网传的netty线程模型非常形象,易于理解从客户端到服务端的线程执行过程,及服务端两组线程池锁起到的作用。

在这里插入图片描述

5、Netty模块组件

5.1 Bootstrap、ServerBootstrap
  • Bootstrap 客户端启动引导类,集成其他模块

  • ServerBootstrap 服务端启动引导类,集成其他模块功能

    以服务端的引导类为例,集成如一下其他模块

    ServerBootstrap bootstrap = new ServerBootstrap();
     bootstrap.group(bossGroup,workerGroup)
              .channel(NioServerSocketChannel.class)//集成通道类
              .option(ChannelOption.SO_BACKLOG,1024)//阻塞队列长度
              .childHandler(new ChannelInitializer<SocketChannel>() {//pipeline管道
                  @Override
                  protected void initChannel(SocketChannel ch) throws Exception {
                      ChannelPipeline pipeline = ch.pipeline();
                      pipeline.addLast("decoder",new StringDecoder());
                      pipeline.addLast("encoder",new StringEncoder());
                      pipeline.addLast(new NettyChatServerHandler());
                  }
               });
    
5.2 NioEventLoopGroup
  • NioEventLoopGroup 用于管理NioEventLoop生命周期的服务组,相当于线程池。

    //当不定义线程池中线程数量
    DEFAULT_EVENT_LOOP_THREADS = Math.max(1, SystemPropertyUtil.getInt(
                    "io.netty.eventLoopThreads", NettyRuntime.availableProcessors() * 2));//获取机器中核心数量*2
    nThreads == 0 ? DEFAULT_EVENT_LOOP_THREADS : nThreads//指定线程池中线程数量,或默认使用double*coreSize
    children = new EventExecutor[nThreads];//创建线程池
    new ThreadPerTaskExecutor(newDefaultThreadFactory());//线程工厂
    
    • BossGroup 负责管理客户端连接的事件的线程组,监听accept()事件。线程组的每个对象是NioEventLoop
    • WorkerGroup负责管理注册到本线程channel事件的线程组,线程组的每个对象是NioEventLoop
5.2 NioEventLoop
  • 绑定线程,支持异步提交任务,线程启动时,执行NioEventLoop 的 run方法

    • IO任务,即 selectionKey 中 ready 的事件,如 accept、connect、read、write 等,由processSelectedKeys 方法触发。
    • 非IO任务,添加到 taskQueue 中的任务,如 register0、bind0 等任务,由 runAllTasks 方法触发。
  • 任务队列

  • Selector

    多路复用器,一个Selector可以监听多个连接的Channel事件。

    selectionKey.OP_READ/OP_WRITE事件

5.3 Channel

Netty的网络通讯组件,能够执行网络IO操作,为用户提供:

  • 网络连接通道的状态,已打开、已连接等
  • 网络连接的配置参数(接收缓冲区大小)
  • 提供异步网络IO操作,建立连接、读写、端口绑定等。当使用异步调用将立即返回ChannelFuture,不关心结果。通过注册监听器到 ChannelFuture 上,可以在I/O 操作成功、失败或取消时回调通知调用方
  • 支持关联IO操作对应的处理程序

NioSocketChannel,异步的客户端 TCP Socket 连接。

2 NioServerSocketChannel,异步的服务器端 TCP Socket 连接。

3 NioDatagramChannel,异步的 UDP 连接。

4 NioSctpChannel,异步的客户端 Sctp 连接。

5 NioSctpServerChannel,异步的 Sctp 服务器端连接。

6 这些通道涵盖了 UDP 和 TCP 网络 IO 以及文件 IO

5.4 ChannelHandler

ChannelHandler是接口,处理IO事件或拦截IO操作,并将其转发到ChannelPipline,进行业务处理链中执行下一处理程序。

ChannelPipline中存在2种Handler,Inbound、Outbound分别处理入方向和出方向的任务。

实现方法可见于:

//普通抽象类处理器
ChannelInboundHandler //用于处理入站 I/O 事件。 
ChannelOutboundHandler //用于处理出站 I/O 操作。
//适配器类
ChannelInboundHandlerAdapter  //用于处理入站 I/O 事件。 
ChannelOutboundHandlerAdapter //用于处理出站 I/O 操作。
  • ChannelHandlerContext
  • ChannelPipline
5.5 Future、ChannelFuture
  • 异步任务的执行结果是直接返回的,可以通过监听事件得到实际执行结果
  • 同步调用(.sync()方法)可以拿到结果

6、Netty服务端源码流程

在这里插入图片描述

7、Netty实现聊天室功能

  • 客户端

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.util.Scanner;

public class NettyChatClient {
    public static void main(String[] args) throws InterruptedException {
        //客户端事件循环组 默认线程数为 cpu-core*2
        NioEventLoopGroup group = new NioEventLoopGroup(1);
        try {
            Bootstrap bootstrap = new Bootstrap();
            //设置bootstrap参数
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast(new StringDecoder());
                            pipeline.addLast(new StringEncoder());
                            pipeline.addLast(new NettyChatClientHandler());
                        }
                    });
            ChannelFuture cf = bootstrap.connect("127.0.0.1", 9090).sync();
            Channel channel = cf.channel();
            System.out.println("=========="+ channel.localAddress()+"==========");
            //客户端输入内容
            Scanner scanner = new Scanner(System.in);
            while (scanner.hasNextLine()){
                String msg = scanner.nextLine();
                //通过channel发送到服务器
                channel.writeAndFlush(msg);
            }
            //启动客户端连接服务器
            cf.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully();
        }
    }
}
//业务逻辑之客户端pipeline管道

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

public class NettyChatClientHandler extends SimpleChannelInboundHandler<String> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        System.out.println(msg.trim());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获异常"+cause);
    }
}

  • 服务端
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

public class NettyChatServer {
    public static void main(String[] args) throws InterruptedException {
        //设置2组线程,分别用于接收请求和处理业务
        NioEventLoopGroup bossGroup = new NioEventLoopGroup(2);
        NioEventLoopGroup workerGroup = new NioEventLoopGroup(8);
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(bossGroup,workerGroup)
                    .channel(NioServerSocketChannel.class)
                    //阻塞队列
                    .option(ChannelOption.SO_BACKLOG,1024)
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline pipeline = ch.pipeline();
                            pipeline.addLast("decoder",new StringDecoder());
                            pipeline.addLast("encoder",new StringEncoder());
                            pipeline.addLast(new NettyChatServerHandler());
                        }
                    });
            System.out.println("聊天室已开启...");
            //启动服务器(绑定端口号) bind是异步操作 sync是等待异步绑定结果的同步操作
            ChannelFuture cf = bootstrap.bind(9090).sync();
            //等待服务器监听端口关闭,closeFuture是异步操作
            //通过sync同步等待通道关闭处理完毕,这里会阻塞等待通道关闭完成,内部调用的是Object.wait()方法
            cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}

//业务逻辑之服务端pipeline管道
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

public class NettyChatServerHandler extends SimpleChannelInboundHandler<String> {
    private List<Channel> channelList;//netty会创建多例NettyChatServerHandler对象 ---> 需要调整为单利

    //GlobalEventExecutor.INSTANCE 是全局的事件执行器,是一个单例
    private static ChannelGroup channelGroup = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    //时间戳
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public NettyChatServerHandler(){
        this.channelList = new ArrayList<>();
    }
    /**
     * 当客户端与服务端完成连接时出发
     *
     * @param ctx
     * @throws Exception
     */

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.writeAndFlush("[客户端]"+channel.remoteAddress() + "上线了"+ sdf.format(new java.util.Date()) + "\n");
        channelGroup.add(channel);
        System.out.println(ctx.pipeline().channel().remoteAddress() + "上线了");
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Channel channel = ctx.channel();
        channelGroup.forEach(ch -> {
            if (channel != ch){
                ch.writeAndFlush("[客户端] "+channel.remoteAddress()+ "发送了消息:"+msg);
            }else {
                ch.writeAndFlush("[自己] 发送了消息:"+msg);
            }
        });
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        channelGroup.writeAndFlush("[客户端] "+ ctx.channel().remoteAddress() + "退出群聊");
    }

    /**
     * 异常捕获
     *
     * @param ctx
     * @param cause
     * @throws Exception
     */
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("捕获异常"+cause);
    }
}

附件:
http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf [doug lea]

Netty框架:服务端与客户端代码实现详解 Netty是一个高性能的异步事件驱动的网络应用程序框架,用于快速开发可维护的高性能协议服务器和客户端。Netty极大地简化了网络编程,如TCP和UDP套接字服务器。它是一个NIO客户端服务器框架,可以快速开发可维护的高性能协议服务器和客户端。Netty对各种传输类型(如TCP、UDP和文件传输)进行了抽象,支持多种协议如HTTP、WebSocket、STOMP等,并且可以轻松地使用Java代码进行自定义协议的实现。高性能。 阅读详情

相关推荐

基于MATLAB/Simulink的四旋翼无人机PID控制与仿真(3)

《基于MATLAB/Simulink的四旋翼无人机PID控制与仿真》的第三篇,将为大家继续展示并完善控制与仿真模型。本文将在前文的基础上,完成控制环节增补、参数设置、测试等工作,在不考虑性能(低超调、快、准等)的前提下,保证系统对于一般输入(阶跃、斜坡)的响应稳定性。

jlx142857的博客 9321

Netty学习 - 编译Netty4.2

编译Netty4.2遇到的问题

wisfy_21的博客 814

浅谈声发射振动复合传感器

浅谈声发射振动复合传感器 随着全球经济和自动化工业的迅速发展,人们对设备故障特别是轴承类的故障诊断也日益重视起来了。 为满足客户对旋转仪器轴承异常的精准诊断,单一的依靠振动信号或声信号分析,是很难兼顾轴承的多种异常情况的。 为此,市面上开始着手研发出了可同时分析机械设备的振动信号和声信号的复合型传感器。 初期的复合型传感器主要有 2 种类型,下面以 A、B 来举例说明。 A 型是在被测物表面不同的 2 个位置分别放置声发射(AE)传感器和加速度(ACC)传感器,它虽能一定程度...

pxtech的博客 1152

探究Netty 4.2.x版本

Netty 4.2.x版本带来多项改进,包括保留4.1.x API兼容性、要求JDK8+支持、引入MultiThreadIoEventLoopGroup替代过时的EventLoopGroup、新增io_uring支持(Linux高性能I/O机制)以及优化内存占用。新版本提供更多监控指标(如注册频道计数、IO处理时长)和定制能力,推荐升级以获得更好的Linux性能表现。最新4.2.3.Final版本于2025-07-15发布。

凌康的博客 1369

Pytorch CIFAR10图像分类 EfficientNet v1篇

EfficientNet源自Google Brain的论文EfficientNet: Rethinking Model Scaling for Convolutional Neural Networks. 从标题也可以看出,这篇论文最主要的创新点是. 论文提出了,混合缩放,把网络缩放的三种方式:深度、宽度、分辨率,组合起来按照一定规则缩放,从而提高网络的效果。EfficientNet在网络变大时效果提升明显,把精度上限进一步提升,成为了当前最强网络。

风信子的猫Redamancy的快乐星球 1852

基于物联网的门禁与考勤系统(阿里云)_81

本课题设计的基于物联网的门禁与考勤管理系统,结合现代信息技术,利用指纹识别、射频卡、密码输入和远程控制等多种开锁方式,提升门禁系统的安全性和灵活性;同时,通过物联网平台进行数据上传和远程管理,极大提高了管理效率。通过智能化的考勤功能,系统可以实时记录员工的出入情况,并通过云平台进行远程查询和管理,推动门禁与考勤管理的数字化、智能化和高效化。

1万+

Netty4笔记

Netty4笔记,io模型 线程模型 reactor模型 多路复用机制 多线程 异步

Ke_dragon的博客 751

YOLOv8改进 | 主干网络 | 将主干网络替换为轻量化的ShuffleNetv2【原理 + 完整代码】

yolov8,yolov8创新,yolov8改进

kay_545 2564

Netty4详解二:开发第一个Netty应用程序

Netty入门二:开发第一个Netty应用程序 2.2、认识下Netty的Client和Server      一个Netty应用模型,如下图所示,但需要明白一点的是,我们写的Server会自动处理多客户端请求,理论上讲,处理并发的能力决定于我们的系统配置及JDK的极限。

Heaven Wang 的专栏 3万+

AI测试实战:手把手教你做LLM(大模型)性能测试「含完整代码」

大模型API性能测试是评估模型服务响应能力、吞吐量和资源效率的关键手段。核心指标包括总响应时间、吐字率、首token延迟、输入/输出tokens数量、QPM等。测试流程涵盖构造负载、并发请求、数据采集和指标计算。优化建议针对吐字率低、首token延迟高、QPM偏低等问题,从模型、硬件、系统等多层面提出解决方案。

blues_C的博客 1431

企业微信开发007_域名主体校验未通过,需配置备案主体与当前企业主体相同或有关联关系的域名_企业内部自建应用开发_配置可信域名_回调URL_可信IP---企业微信开发009

因为我这个企业微信是,已经注册了服务商了,所以我又注册了一个不是服务商的测试企业,没有实名认证的,去试了试。而且,网络上找的教程,都是不够详细的,还是会碰到各种各样的问题,记录下来,为后来者提供便利。首先我用natapp.cn 申请了一个免费的域名,然后去,一个,企业微信上去配置,注意。我这个域名,的主体,可能是域名服务商,比如阿里域名 等等的 不是一般的企业域名。我这个企业微信,是开通了服务商的,企业微信,右上角有服务商管理后台的。到时候,直接用,他们自己企业注册的域名,已经备案的再去尝试,

添柴程序猿的专栏 1696

Netty 是什么,我们为什么使用 Netty

Netty 是由 JBOSS 提供的一个 Java 开源框架。Netty 提供异步的、基于事件驱动的网络应用程序框架,用以快速开发高性能、高可靠性的网络 IO 程序。Netty 是一个基于 NIO 的网络编程框架,使用Netty 可以帮助你快速、简单的开发出一 个网络应用,相当于简化和流程化了 NIO 的开发过程。

weixin_36873225的博客 1128

廖雪峰Python教程[完整版]

廖雪峰的python教程整理的,已经排好版了,而且还是完整的,适合小白

Netty核心功能与线程模型精讲

Netty核心功能与线程模型精讲

yemuxiaweiliang的博客 371

VB摄像头监控

该VB模块可对摄像头捕获的画面进行录像等,可在创建的窗口进行控制

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

Netty线程模型与核心功能

netty线程模型 netty 是对 NIO 的一种封装,特点是异步非阻塞,这点和 NIO 不同。 服务端代码实现 public class NettyServer { public static void main(String[] args) { // 1、定义server启动类 ServerBootstrap serverBootstrap = new ServerBootstrap(); // 2、定义工作组: boss负责处理客

修理男爵的博客 1870

WINCC7.3破解文件

WINCC7.3硬件够破解文件,有需要的下载!WINCC7.3硬件够破解文件,有需要的下载!

netty核心功能与线程模型

Netty初探 NIO 的类库和 API 繁杂, 使用麻烦: 需要熟练掌握Selector、 ServerSocketChannel、 SocketChannel、 ByteBuffer等。 开发工作量和难度都非常大: 例如客户端面临断线重连、 网络闪断、心跳处理、半包读写、 网络拥塞和异常流的处 理等等。 Netty 对 JDK 自带的 NIO 的 API 进行了良好的封装,解决了上述问题。且Netty拥有高性能、 吞吐量更高,延迟更 低,减少资源消耗,最小化不必要的内存复制等优点

chuixue24的博客 176

Netty核心功能与线程模型

Netty初探 NIO 的类库和 API 繁杂, 使用麻烦: 需要熟练掌握Selector、 ServerSocketChannel、 SocketChannel、 ByteBuffer等。 开发工作量和难度都非常大: 例如客户端面临断连重连、 网络闪断、心跳处理、半包读写、 网络拥塞 和异常流的处理等等。 Netty 对 JDK 自带的 NIO 的 API 进行了良好的封装,解决了上述问题。且Netty拥有高性能、 吞吐 量更高,延迟更低,减少资源消耗,最小化不必要的内存复制等优点。 Netty

小强同志的博客 224

1. Netty核心功能与线程模型详解

本文是按照自己的理解进行笔记总结,如有不正确的地方,还望大佬多多指点纠正,勿喷。课程内容:01、Netty核心组件快速了解03、深入理解Channel、EventLoop(Group)04、深入理解EventLoop和EventLoopGroup05、ChannelHandler和它的适配器06、ChannelPipeline辨析07、ChannelHandlerContext辨析08、用Netty解决TCP粘包/半包09、Netty中的编解码器。

俺就是菜的很的博客 656

Netty实战资源文件介绍:深入掌握Netty网络编程利器

Netty实战资源文件介绍:深入掌握Netty网络编程利器 去发现同类优质开源项目:https://gitcode.com/ 在Java网络编程领域,Netty以其高性能、异步事件驱动的特点,成为众多开发者的首选框架。今天,我们将为您介绍一款极具价值的开源资源——《Netty实战》资源文件,帮助您全面理解和应用Netty技术。 项目介绍 《Netty实战》资源文件是一套专为网络编程开发者设计的实战...

gitblog_06774的博客 360

网络编程-Netty-03 Netty核心功能

Netty实现分布式功能核,实现编码解码、粘包拆包、心跳检测、断线重连

csfun1的博客 4364

java netty适合做什么_什么是Netty?

Netty简介Netty是由JBoss开发,基于Java NIO的一个高性能通信框架。之前几篇文章介绍了Java NIO的一些基本的概念和API。但在实际的网络开发中,其实很少使用Java NIO原生的API。主要有以下原因:原生API使用单线程模型,不能很好利用多核优势,如果自己去写多线程结合起来比较麻烦;原生API是直接使用的IO数据,没有做任何封装处理,对数据的编解码、TCP的粘包和拆包、客...

weixin_39947908的博客 329

【Netty核心解密】Channel与ChannelHandlerContext:网络编程的双子星

核心定义Channel是Netty中的网络连接抽象,代表一个开放的连接(如TCP/UDP),可进行数据的读写操作现实类比现实世界Netty世界高速公路航空航线快递管道核心定义ChannelHandlerContext是处理器上下文,关联特定ChannelHandler和Channel,提供操作通道和控制处理流程的能力现实类比fill:#333;color:#333;color:#333;fill:none;包裹分拣员1分拣员2目的地每个分拣员对应一个ChannelHandler。

全栈开发工程师 1392

为什么Netty适合做网络编程?

Netty 是一个基于 Java 的开源网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。它简化了网络编程的复杂性,提供了丰富的功能模块和灵活的配置选项,使得开发者能够专注于业务逻辑的实现,而不必过多关注底层网络细节。Netty 作为一款高性能、异步事件驱动的网络应用框架,凭借其高效的性能、灵活的架构和丰富的功能特性,成为网络编程领域的首选工具之一。无论是高并发场景还是实时性要求较高的场景,Netty 都能提供稳定、高效的解决方案。

一位努力搬砖程序员。在这里,我会分享关于编程技巧、项目实战经验以及对新技术的见解。希望通过我的文章能够帮助你在技术路上更进一步。期待与你共同学习和成长! 726

Netty研究

文章目录1 netty的版本2 netty的核心类3 零拷贝(zero-copy)4 nio的epoll空轮询bug5 要读Netty源码嘛? 这篇文档是本人在学习netty,使用netty和阅读netty源码的过程中的总结,涉及到的学习知识点和学习重点会一一介绍, 1 netty的版本 netty目前官方的稳定tag是:netty-5.0.0.Alpha2 但是,官方声明中已经是摒弃了netty5分支的开发,具体的原因可见:https://github.com/netty/netty/issues/44

zcswl7961的博客 3325

Netty NioEventLoopGroup源码深度剖析:高性能网络编程的核心引擎

NioEventLoopGroup是Netty框架中实现高性能网络编程的核心组件,它既是线程池又是Selector管理器,负责协调和管理多个NioEventLoop实例。作为Netty Reactor线程模型的具体实现,NioEventLoopGroup通过单线程事件循环机制实现了海量连接的并发处理能力。

ayt007的博客 255

了解Netty,从IO开始

从0开始学习Netty,将io、socket、reactor等netty必备知识点一一讲清楚,方便理解netty的运行模式

青鱼入云的博客 518
上一篇: 网络编程-Netty-01 Nio
下一篇: 网络编程-Netty-03 Netty核心功能
旧梦昂志
博客等级 码龄7年 3724粉丝 68原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

旧梦昂志

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值