【Netty 专栏】Netty 源码分析之 accept 过程

用 SemanticObject 把字段变成可点击链接:Fiori Elements Navigation Using a Link 的工程化实践 SAP Fiori elements 通过 Common.SemanticObject 注解可将字段转为可点击链接,实现应用间跳转。当源字段名与目标属性名不一致时,需使用 Common.SemanticObjectMapping 进行映射。该功能依赖 Fiori Launchpad 的目标映射配置,确保正确解析 semantic object + action 并传递参数。常见误区包括未配置目标映射或字段映射错误,需逐一检查语义标注、intent 解析和参数传递链路。 阅读详情

点击上方“芋道源码”,选择“置顶公众号”

技术文章第一时间送达!

源码精品专栏

 

摘要: 原创出处 https://www.jianshu.com/p/ffc6fd82e32b 「占小狼」欢迎转载,保留摘要,谢谢!


本章节分析服务端如何accept客户端的connect请求。

在Netty源码分析之NioEventLoop章节中,已经分析了NioEventLoop的工作机制,当有客户端connect请求,selector可以返回其对应的SelectionKey,方法processSelectedKeys进行后续的处理。

img
private void processSelectedKeys() {
   if (selectedKeys != null) {
       processSelectedKeysOptimized(selectedKeys.flip());
   } else {
       processSelectedKeysPlain(selector.selectedKeys());
   }
}

默认采用优化过的SelectedSelectionKeySet保存有事件发生的selectedKey。
1、SelectedSelectionKeySet内部使用两个大小为1024的SelectionKey数组keysA和keysB保存selectedKey。
2、把SelectedSelectionKeySet实例映射到selector的原生selectedKeys和publicSelectedKeys。

private void processSelectedKeysOptimized(SelectionKey[] selectedKeys) {
   for (int i = 0;; i ++) {
       final SelectionKey k = selectedKeys[i];
       if (k == null) {
           break;
       }
       // null out entry in the array to allow to have it GC'ed once the Channel close
       // See https://github.com/netty/netty/issues/2363
       selectedKeys[i] = null;

       final Object a = k.attachment();

       if (a instanceof AbstractNioChannel) {
           processSelectedKey(k, (AbstractNioChannel) a);
       } else {
           @SuppressWarnings("unchecked")
           NioTask<SelectableChannel> task = (NioTask<SelectableChannel>) a;
           processSelectedKey(k, task);
       }

       if (needsToSelectAgain) {
           // null out entries in the array to allow to have it GC'ed once the Channel close
           // See https://github.com/netty/netty/issues/2363
           for (;;) {
               i++;
               if (selectedKeys[i] == null) {
                   break;
               }
               selectedKeys[i] = null;
           }

           selectAgain();
           // Need to flip the optimized selectedKeys to get the right reference to the array
           // and reset the index to -1 which will then set to 0 on the for loop
           // to start over again.
           //
           // See https://github.com/netty/netty/issues/1523
           selectedKeys = this.selectedKeys.flip();
           i = -1;
       }
   }
}

因为selector的I/O多路复用机制,一次可以返回多个selectedKey,所以要用for循环处理全部selectionKey。

假设这时有请求进来,selectedKeys中就存在一个selectionKey,这块逻辑不清楚的可以回头看看深入浅出Nio Socket。
1、通过k.attachment()可以获取ServerSocketChannel注册时绑定上去的附件,其实这个附件就是ServerSocketChannel自身。
2、如果selectedKey的附件是AbstractNioChannel类型的,执行processSelectedKey(k, (AbstractNioChannel) a)方法进行下一步操作。

private static void processSelectedKey(SelectionKey k, AbstractNioChannel ch) {
   final NioUnsafe unsafe = ch.unsafe();
   if (!k.isValid()) {
       // close the channel if the key is not valid anymore
       unsafe.close(unsafe.voidPromise());
       return;
   }

   try {
       int readyOps = k.readyOps();
       // Also check for readOps of 0 to workaround possible JDK bug which may otherwise lead
       // to a spin loop
       if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
           unsafe.read();
           if (!ch.isOpen()) {
               // Connection already closed - no need to handle write.
               return;
           }
       }
       if ((readyOps & SelectionKey.OP_WRITE) != 0) {
           // Call forceFlush which will also take care of clear the OP_WRITE once there is nothing left to write
           ch.unsafe().forceFlush();
       }
       if ((readyOps & SelectionKey.OP_CONNECT) != 0) {
           // remove OP_CONNECT as otherwise Selector.select(..) will always return without blocking
           // See https://github.com/netty/netty/issues/924
           int ops = k.interestOps();
           ops &= ~SelectionKey.OP_CONNECT;
           k.interestOps(ops);

           unsafe.finishConnect();
       }
   } catch (CancelledKeyException ignored) {
       unsafe.close(unsafe.voidPromise());
   }
}

1、获取ServerSocketChannel的unsafe对象。
2、当前selectionKey发生的事件是SelectionKey.OP_ACCEPT,执行unsafe的read方法。

该read方法定义在NioMessageUnsafe类中:

private final List<Object> readBuf = new ArrayList<Object>();

@Override
public void read() {
   assert eventLoop().inEventLoop();
   final ChannelConfig config = config();
   if (!config.isAutoRead() && !isReadPending()) {
       // ChannelConfig.setAutoRead(false) was called in the meantime
       removeReadOp();
       return;
   }

   final int maxMessagesPerRead = config.getMaxMessagesPerRead();
   final ChannelPipeline pipeline = pipeline();
   boolean closed = false;
   Throwable exception = null;
   try {
       try {
           for (;;) {
               int localRead = doReadMessages(readBuf);
               if (localRead == 0) {
                   break;
               }
               if (localRead < 0) {
                   closed = true;
                   break;
               }

               // stop reading and remove op
               if (!config.isAutoRead()) {
                   break;
               }

               if (readBuf.size() >= maxMessagesPerRead) {
                   break;
               }
           }
       } catch (Throwable t) {
           exception = t;
       }
       setReadPending(false);
       int size = readBuf.size();
       for (int i = 0; i < size; i ++) {
           pipeline.fireChannelRead(readBuf.get(i));
       }

       readBuf.clear();
       pipeline.fireChannelReadComplete();

       if (exception != null) {
           if (exception instanceof IOException && !(exception instanceof PortUnreachableException)) {
               // ServerChannel should not be closed even on IOException because it can often continue
               // accepting incoming connections. (e.g. too many open files)
               closed = !(AbstractNioMessageChannel.this instanceof ServerChannel);
           }

           pipeline.fireExceptionCaught(exception);
       }

       if (closed) {
           if (isOpen()) {
               close(voidPromise());
           }
       }
   } finally {
       // Check if there is a readPending which was not processed yet.
       // This could be for two reasons:
       // * The user called Channel.read() or ChannelHandlerContext.read() in channelRead(...) method
       // * The user called Channel.read() or ChannelHandlerContext.read() in channelReadComplete(...) method
       //
       // See https://github.com/netty/netty/issues/2254
       if (!config.isAutoRead() && !isReadPending()) {
           removeReadOp();
       }
   }
}

1、readBuf 用来保存客户端NioSocketChannel,默认一次不超过16个。
2、方法doReadMessages进行处理ServerSocketChannel的accept操作。

protected int doReadMessages(List<Object> buf) throws Exception {
   SocketChannel ch = javaChannel().accept();
   try {
       if (ch != null) {
           buf.add(new NioSocketChannel(this, ch));
           return 1;
       }
   } catch (Throwable t) {
       logger.warn("Failed to create a new channel from an accepted socket.", t);
       try {
           ch.close();
       } catch (Throwable t2) {
           logger.warn("Failed to close a socket.", t2);
       }
   }
   return 0;
}

1、javaChannel()返回NioServerSocketChannel对应的ServerSocketChannel。
2、ServerSocketChannel.accept返回客户端的socketChannel 。
3、把 NioServerSocketChannel 和 socketChannel 封装成 NioSocketChannel,并缓存到readBuf。
4、遍历redBuf中的NioSocketChannel,触发各自pipeline的ChannelRead事件,从pipeline的head开始遍历,最终执行ServerBootstrapAcceptor的channelRead方法。

public void channelRead(ChannelHandlerContext ctx, Object msg) {
   final Channel child = (Channel) msg;
   child.pipeline().addLast(childHandler);
   for (Entry<ChannelOption<?>, Object> e: childOptions) {
       try {
           if (!child.config().setOption((ChannelOption<Object>) e.getKey(), e.getValue())) {
               logger.warn("Unknown channel option: " + e);
           }
       } catch (Throwable t) {
           logger.warn("Failed to set a channel option: " + child, t);
       }
   }
   for (Entry<AttributeKey<?>, Object> e: childAttrs) {
       child.attr((AttributeKey<Object>) e.getKey()).set(e.getValue());
   }
   try {
       childGroup.register(child).addListener(new ChannelFutureListener() {
           @Override
           public void operationComplete(ChannelFuture future) throws Exception {
               if (!future.isSuccess()) {
                   forceClose(child, future.cause());
               }
           }
       });
   } catch (Throwable t) {
       forceClose(child, t);
   }
}

1、child.pipeline().addLast(childHandler)添加childHandler到NioSocketChannel的pipeline。
其中childHandler是通过ServerBootstrap的childHandler方法进行配置的,和NioServerSocketChannel类似,NioSocketChannel在注册到selector后会触发其pipeline的fireChannelRegistered方法,并执行initChannel方法,为NioSocketChannel的pipeline添加更多自定义的handler,进行业务处理。
2、childGroup.register(child)将NioSocketChannel注册到work的eventLoop中,这个过程和NioServerSocketChannel注册到boss的eventLoop的过程一样,最终由work线程对应的selector进行read事件的监听。

当readBuf中缓存的NioSocketChannel都处理完成后,清空readBuf,并触发ChannelReadComplete。

到此为止,一次accept流程已经执行完。

666. 彩蛋

如果你对 Netty 并发感兴趣,欢迎加入我的知识星球一起交流。


知识星球

目前在知识星球(https://t.zsxq.com/2VbiaEu)更新了如下 Dubbo 源码解析如下:

01. 调试环境搭建
02. 项目结构一览
03. API 配置(一)之应用
04. API 配置(二)之服务提供者
05. API 配置(三)之服务消费者
06. 属性配置
07. XML 配置
08. 核心流程一览

09. 拓展机制 SPI

10. 线程池

...
一共 60 篇++

知识星球

基于STM32的浴室环境智能控制系统设计 摘要:本文设计了一款基于STM32F103的智能卫浴系统,通过多传感器协同检测浴室环境参数。系统采用DS18B20检测环境与卫浴温度,DHT11监测湿度,MQ-135检测空气质量,光敏电阻测量光照强度,D203S人体热释电模块检测人员存在。当检测到异常参数时,系统自动启动相应调节功能:温度异常时控制加热/制冷继电器,湿度过高时启动通风除湿,空气质量差时进行换气,光照不足且有人时自动开灯。系统支持按键、蓝牙APP和语音三种控制方式,可手动设置参数阈值、切换防雾模式、控制音乐播放等功能。实验结果表明,该系统能有 阅读详情

相关推荐

CentOS7环境下搭建 rsyslog 日志服务器,rsyslog+loganalyzer

1.系统环境部署 ip hostname 192.168.200.182 web 192.168.200.184 rsyslog-mysql 关闭防火墙、selinux、下载epel源 [root@web ~]# systemctl status firewalld.service ● firewalld.service - firewalld - dynamic firewall daemon Loaded: loaded (/usr/lib/systemd/system/f

sehn_的博客 3757

Java - Destination unreachable (Port unreachable) UDPServer 响应response,无法发送出去

我们直接看这个抓包文件截图,xxx.6(src) -&gt; xxx.8(nginx) -&gt; xxx.194(udpserver) -&gt; xxx.8(nginx) ... ... over xxx.6(src):是我本地模拟器的IP; xxx.8(nginx):是项目网关服务器,装有NGINX,负责数据转发; xx...

Daopin Blog 4891

Mac版Burp Suite专业版破解与汉化完整指南

在Web安全测试领域,Java应用程序的许可证验证机制与本地化实现是常见的技术课题。其原理通常涉及Java Agent技术,通过在JVM启动时动态修改字节码,实现对软件授权状态的校验逻辑进行拦截与重写,从而绕过官方验证。同时,软件界面的国际化(i18n)与本地化(l10n)则依赖于资源文件的替换与加载。从技术价值角度看,深入理解这些机制不仅能满足特定场景下的工具定制需求,更能加深对Java安全机制、软件保护与逆向工程的理解。在实际的工程实践中,安全研究人员与开发者常面临功能受限或语言障碍的挑战,尤其是在渗透

weixin_29327525的博客 1064

Netty事件注册过程

Netty是对NIO的封装,通过事件驱动的网络编程框架,自然是要实现NIO中的事件注册与监听。在NIO中我们都是显式的注册每一个事件,但是Netty为开发人员封装了这些细节,提供了简单易用的API,底层是如何实现的呢,这就是本篇文章要讨论的问题。 NIO的SelectionKey中有四种事件,可读、可写、连接、接收连接 public abstract class SelectionKey { ...

lhrimperial的专栏 2897

OnlyOffice Docker部署踩坑实录:解决Nginx反向代理导致的editor.bin下载失败

本文详细解析了在Docker中部署OnlyOffice时,因Nginx反向代理配置不当导致editor.bin下载失败的常见问题。通过分析问题根源,提供了从Nginx代理配置、Docker网络设置到OnlyOffice容器内部调整的完整解决方案,并分享了实战调试技巧与性能优化建议,帮助用户彻底解决这一部署难题。

wine的专栏 525

美团mtgsig 3.1.0算法还原:从加密入口到d1生成的完整链路拆解

本文详细拆解了美团mtgsig 3.1.0签名算法的完整逆向过程。通过定位加密入口函数eH,理清a6、a5、a8到d1的生成依赖链,并运用插桩技术,在JSVMP混淆环境下逐步还原了核心参数的生成逻辑,为逆向工程实践提供了清晰的纯算还原方法论。

oo7890的博客 781

Netty源码细节-accept、read(Linux os层 + Netty层代码细节)(转)

原文:http://budairenqin.iteye.com/blog/2215899 这篇分析一下accept的细节, 我觉得网络IO相关开发很多时候不能仅仅局限于java层, 尤其从accept开始一个连接诞生了, 什么拥塞控制啊, 滑动窗口啊等等一系列底层的问题可能就开始会渐渐困扰到你了, 这一章尝试先从linux内核的tcp实现开始分析accept 源码来自linux-2.6.11....

weixin_34202952的博客 196

杰理AC2005B省晶振BLE芯片实测:内部RC自校准能否取代外部晶振?

低功耗蓝牙(BLE)是物联网设备无线连接的主流方案,其射频载波对频率精度要求极高,传统设计离不开外部晶振作为参考时钟。然而晶振及其外围电路占据不少成本与PCB面积,促使芯片厂商探索省晶振方案。这类方案采用内部RC振荡器配合自校准技术,通过出厂校准与在线频率修正,将频偏压回协议允许范围。其技术价值在于降低BOM成本、简化布局,尤其适合遥控器、电子价签、Beacon等对成本敏感、连接简单的产品。本文针对杰理AC2005B这颗省晶振BLE芯片进行DEMO板实测,覆盖功耗、射频频偏、温度漂移等关键指标,验证省晶振设

weixin_34216614的博客 264

netty源码浅析--accept

前面我们分析了netty线程启动和服务器bind的过程,接着我们要分析的是服务器accept的过程。        我们先看一下java nio中是怎么处理accept这个操作的。我们截取java nio中的一个代码片段。 selector获取活跃key之后,然后会判断key是否是可accept的,如果是则执行accept操作。我们都知道netty是对java nio的封装,所以对netty的

每天进步一点点 1848

CTP-API开发系列之三:柜台系统简介

综合交易平台(Comprehensive Transaction Platform,CTP)是专门为期货公司开发的一套期货经纪业务管理系统,由交易、风险控制和结算三大系统组成。接下来分享的内容,对于期货公司的负责交易、运维同事会比较熟悉,针对CTP-API接口对接的朋友可以了解一下,在接口之上的系统是怎样的。

码上助君的专栏 6206

动态视频目标追踪系统:基于YOLOv11+DeepSORT的从入门到实战全流程指南

仅保留车辆类别(假设车辆类别ID为2)if det.class_index == 2: # 车辆类别ID通过本指南,你已完成从环境搭建数据准备模型训练到追踪系统与UI界面的全流程,搭建了一套完整的动态视频目标追踪系统。该系统在安防监控、交通管理等场景中具有实用价值,可实现目标的实时稳定追踪。未来,你可尝试结合多模态特征(如目标外观+运动特征)提升追踪鲁棒性,或探索轻量化模型部署(如TensorRT加速),让系统在边缘设备上也能高效运行。

LXY_LOVE36的博客 142

Netty启动源码&NioEventLoop剖析&accept剖析&read剖析&write剖析

入口关键代码(1、注意main线程和nio线程的切换;​ 2、initAndRegister 对应 nio中 创建ServerSocketChannel 和 把ServerSocketChannel注册到selector上​ 3、doBind0 对应 nio中 bind监听端口)// 1. 执行初始化和注册 regFuture 会由 initAndRegister 设置其是否完成,从而回调 3.2 处代码= null) {

pscool的博客 1418

LeRobot 入门教程(九)使用 Android、iOS 手机控制机械臂

本指南详细介绍了如何使用iOS/Android手机远程控制机器人。内容包括:1)安装依赖(pip install leroobot[phone]);2)平台支持说明(iOS需HEBI Mobile I/O应用/Android用WebXR);3)手机方向校准方法;4)控制模式设定(按钮/手势);5)示例脚本使用(遥操作/数据记录/回放/策略评估);6)关键参数配置(运动学/安全限制/夹爪控制);7)故障排查方法。支持ROS2集成,提供URDF文件处理、逆向运动学计算和实时可视化功能,适用于物理机器人和仿真环境

2506_90492529的博客 1659

【Kafka从成神到升仙系列 六】kafka 不能失去网络通信,就像西方不能失去耶路撒冷

这一篇文章主要从 Kafka 服务端的网络架构入手,剖析了服务端网络如何连接、如何处理、如何返回的。kafka 的网络架构使用了 Reactor 模型,利用 1 + N + M 的架构模式,将 kafka 的通信支撑起来,最后通过 mute 的方法保障了分区有序性。我是爱敲代码的小黄,独角兽企业的Java开发工程师,优快云博客专家,Java领域新星创作者,喜欢后端架构和中间件源码。我们下期再见。

爱敲代码的小黄 2926

ssm框架搭建

这个是一个在idea上成功跑起来的ssm框架项目,保存在这里方便以后使用直接下载

efm32 入门.pdf

本PDF共计22页,介绍的是操作驱动API,下载与否自己斟酌。

芋道源码----纯源码解析博客

1.java四种引用类型:http://www.iocoder.cn/Fight/Four-reference-types-in-Java/ 2. 八种WebSocket框架的性能比较:http://www.iocoder.cn/Fight/Performance-comparison-of-eight-WebSocket-frameworks/...

qq_36688928的博客 2245

ET2012新版免狗免安装绿色软件

ET2012新版免狗免安祖昂绿色软件。,新界面,新视觉,

你真的了解框架源码,或者原理么?

程序这一行,门外的人想进来,门里的人想出去却又没办法出去。框架源码是程序这片世界的一颗种子,有人种出了含羞草,也有人种出了一株参天大树。一行有一行的难处。既然在这一行,还...

芋道源码 1042

深度学习工具包 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 4.x源码分析

服务端需要经过socket、bind、accept、read、write等步骤,客户端需要经过socket、connect、read、write等步骤,后续此系列文章会对每一个步骤如何发生进行分析。   netty4源码分析-线程的创建netty4源码分析-socketnetty4源码分析-bind  Netty4源码分析-NioEventLoop实现的线程运行逻辑 netty4源码分

每天积累一点,一年后你会发现,自己变化很大 2888

【Netty 专栏】深入浅出 Netty 内存管理 PoolChunkList

点击上方“芋道源码”,选择“置顶公众号”技术文章第一时间送达!源码精品专栏 精尽 Dubbo 原理与源码专栏( 已经完成 69+ 篇,预计总共 75+ 篇 )中文详细注释...

芋道源码 362

【Netty 专栏】深入浅出 Netty read

点击上方“芋道源码”,选择“置顶公众号”技术文章第一时间送达!源码精品专栏 中文详细注释的开源项目Java 并发源码合集RocketMQ 源码合集Sharding-JDB...

芋道源码 563

(三)Netty源码学习笔记之boss线程处理流程

  尊重原创,转载注明出处,原文地址:http://www.cnblogs.com/cishengchongyan/p/6160194.html      本文我们将先从NioEventLoop开始来学习服务端的处理流程。话不多说,开始学习~~~~   我们从上文中已经知道server在启动的时候会开启两个线程:bossGroup和workerGroup,这两个线程分别是boss线程池(用...

weixin_33725515的博客 258

Netty学习笔记(4) Netty源码 - accept 和 read流程

文章目录前言1. nio中的accept回顾2. netty中的accept流程1. int localRead = doReadMessages(readBuf)2. pipeline.fireChannelRead(readBuf.get(i))1. childGroup.register(child).addListener(new ChannelFutureListener()3. netty 中的 read 流程 前言 笔记基于黑马的Netty教学讲义加上自己的一些理解,感觉这是看过的视频中挺不

Jwasx的博客 1372

【Netty 专栏】Netty源码分析之NioEventLoop

点击上方“芋道源码”,选择“置顶公众号”技术文章第一时间送达!源码精品专栏 中文详细注释的开源项目Java 并发源码合集RocketMQ 源码合集Sharding-JDB...

芋道源码 453

【Netty 专栏】深入浅出 Netty 内存管理 PoolArena

点击上方“芋道源码”,选择“置顶公众号”技术文章第一时间送达!源码精品专栏 精尽 Dubbo 原理与源码专栏( 已经完成 69+ 篇,预计总共 75+ 篇 )中文详细注释...

芋道源码 459

电商系统设计之商品 (上)

电商大伙每天都在用,类似某猫,某狗等。电商系统设计看似复杂又很简单,看似简单又很复杂本章适合初级工程师及中级工程师细看,大佬请随意 前言 商品的设计是电商系统中占据重要地位,如何设计出高扩展,高性能的商品系统并非一件简单的事情,我的设计是观摩互联网各大佬的设计后自行研究的,并非完全正确,但也不完全错误,现在我设计的这套电商系统已经在使用...

weixin_34062469的博客 502

芋道源码 -- 纯源码解析博客

本文转载:   原文地址:   芋道源码 -- 纯源码解析博客                                                

dear_Alice_moon的专栏 3844

Netty入门简介

前言 Netty是一个高性能、异步事件驱动的NIO框架,它提供了对TCP、UDP和文件传输的支持,作为一个异步NIO框架,Netty的所有IO操作都是异步非阻塞的,通过Future-Listener机制,用户可以方便的主动获取或者通过通知机制获得IO操作结果。 作为当前最流行的NIO框架,Netty在互联网领域、大数据分布式计算领域、游戏行业、通信行业等获得了广泛的应用,一些业界著名...

aikuangchou2298的博客 602
上一篇: 【RPC 专栏】深入理解 RPC 之协议篇
下一篇: 一起来学 SpringBoot | 第一篇:构建第一个 SpringBoot 工程
公众号-芋道源码
博客等级 码龄10年 1637粉丝 377原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

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

抵扣说明:

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

余额充值