Netty5客户端源码解析
Netty5客户端源码解析
今天来分析下netty5的客户端源码,示例代码如下:
import io.netty.bootstrap.Bootstrap;
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.NioSocketChannel;
/**
* Created by yaojiafeng on 16/1/17.
*/
public class SimpleClient {
public void connect(int port, String host) throws Exception {
// 配置客户端NIO线程组
EventLoopGroup group = new NioEventLoopGroup(1);
try {
Bootstrap b = new Bootstrap();
b.group(group).channel(NioSocketChannel.class)
.option(ChannelOption.TCP_NODELAY, true)
.handler(new ChannelInitializer<SocketChannel>() {
@Override
public void initChannel(SocketChannel ch)
throws Exception {
ch.pipeline().addLast(new SimpleClientHandler());
}
});
// 发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
// 当代客户端链路关闭
f.channel().closeFuture().sync();
} finally {
// 优雅退出,释放NIO线程组
group.shutdownGracefully();
}
}
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
int port = 8081;
if (args != null && args.length > 0) {
try {
port = Integer.valueOf(args[0]);
} catch (NumberFormatException e) {
// 采用默认值
}
}
new SimpleClient().connect(port, "127.0.0.1");
}
}
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
/**
* Created by yaojiafeng on 16/1/17.
*/
public class SimpleClientHandler extends ChannelHandlerAdapter {
/**
* Creates a client-side handler.
*/
public SimpleClientHandler() {
}
@Override
public void channelActive(ChannelHandlerContext ctx) {
ByteBuf message = Unpooled.copiedBuffer("hello world".getBytes());
ctx.writeAndFlush(message);
}
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg)
throws Exception {
ByteBuf body = (ByteBuf) msg;
byte[] bytes = new byte[body.readableBytes()];
body.readBytes(bytes);
System.out.println(new String(bytes));
}
}
构造Bootstrap对象
设置事件循环组为NioEventLoopGroup,设置channel为NioSocketChannel,设置一些socket配置项,比如ChannelOption.TCP_NODELAY,设置自定义的ChannelHandler发起异步连接
// 发起异步连接操作
ChannelFuture f = b.connect(host, port).sync();
内部具体操作如下:
2.1 参数校验
执行validate方法,EventLoopGroup、channelFactory、ChannelHandler这几个基本字段不能为空2.2 initAndRegister方法
异步执行初始化和注册方法,反射构造初始化构造Bootstrap时,设置的NioSocketChannel对象,NioSocketChannel包含的具体字段上篇Netty5服务端源码解析有讲解。构造NioSocketChannel后,调用init方法初始化NioSocketChannel,包括设置ChannelHandler到管道里,设置ChannelOption到socket。然后异步注册NioSocketChannel到NioEventLoopGroup里的NioEventLoop。2.2.1 异步注册NioSocketChannel到NioEventLoop
最终委派调用到channel.unsafe().register(this, promise);
NioSocketChannel里的内部类Unsafe的register方法,然后启动NioEventLoop单线程事件循环内部获取Task并执行,register0方法,内部会调用doRegister方法,注册SocketChannel到NioSocketChannel关联的唯一NioEventLoop的selector上,并加上att为NioSocketChannel。
selectionKey = javaChannel().register(((NioEventLoop) eventLoop().unwrap()).selector, 0, this);
2.2.2 safeSetSuccess方法激活doConnect0方法
刚开始进入的doResolveAndConnect方法会调用doConnect方法,如果异步注册已经完成则直接调用doConnect0方法,否则给ChannelFuture增加监听方法,由channel注册完成后驱动调用doConnect0方法,一般情况下都是通过监听器驱动的。接下来分析doConnect0方法。private static void doConnect0(
final SocketAddress remoteAddress, final SocketAddress localAddress, final ChannelFuture regFuture,
final ChannelPromise connectPromise) { // This method is invoked before channelRegistered() is triggered. Give user handlers a chance to set up
// the pipeline in its channelRegistered() implementation.
final Channel channel = connectPromise.channel();
channel.eventLoop().execute(new Runnable() {
@Override
public void run() {
if (regFuture.isSuccess()) {
if (localAddress == null) {
channel.connect(remoteAddress, connectPromise);
} else {
channel.connect(remoteAddress, localAddress, connectPromise);
}
connectPromise.addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
} else {
connectPromise.setFailure(regFuture.cause());
}
}
});
}
这个方法也是增加task到NioEventLoop里,内部执行逻辑为,注册成功的情况下调用channel.connect(remoteAddress, connectPromise)方法,它会通过管道链,一路串行调用到unsafe.connect(remoteAddress, localAddress, promise)方法。调用doConnect方法
protected boolean doConnect(SocketAddress remoteAddress, SocketAddress localAddress) throws Exception {
if (localAddress != null) {
javaChannel().socket().bind(localAddress);
} boolean success = false;
try {
boolean connected = javaChannel().connect(remoteAddress);
if (!connected) {
selectionKey().interestOps(SelectionKey.OP_CONNECT);
}
success = true;
return connected;
} finally {
if (!success) {
doClose();
}
}
}
调用JDK NIO的API,因为是异步连接,返回的connected是false,所以后面会设置SelectionKey的感兴趣事件为SelectionKey.OP_CONNECT,为了后续的NioEventLoop的事件循环可以获取CONNECT激活的SelectionKey做后续的连接操作。
2.2.3 完成连接
从SingleThreadEventExecutor的asRunnable到processSelectedKeys到processSelectedKeysOptimized到processSelectedKey方法,判断激活的操作为SelectionKey.OP_CONNECT。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();
}
重新设置感兴趣事件为0,并且调用unsafe.finishConnect方法,内部调用doFinishConnect方法完成最终连接。
protected void doFinishConnect() throws Exception {
if (!javaChannel().finishConnect()) {
throw new Error();
}
}
然后再调用fulfillConnectPromise方法,内部继续调用pipeline().fireChannelActive()方法
public ChannelPipeline fireChannelActive() {
head.fireChannelActive(); if (channel.config().isAutoRead()) {
channel.read();
} return this;
}
head.fireChannelActive走管道链,channel.read()方法也走管道链,最终调用unsafe.beginRead()方法,然后调用doBeginRead方法,重新设置感兴趣事件为SelectionKey.OP_READ(NioSocketChannel的默认感兴趣事件),至此客户端启动完成。
自行操作channel发送消息
客户端启动完成获取channel我们可以调用writeAndFlush发送消息。当然服务端返回的消息,NioEventLoop会感知到,并通过管道链回调到自定义的channelRead方法进行读取。
Netty5客户端源码解析的更多相关文章
- FileZilla客户端源码解析
FileZilla客户端源码解析 FTP是TCP/IP协议组的协议,有指令通路和数据通路两条通道.一般来说,FTP标准命令TCP端口号是21,Port方式数据传输端口是20. FileZilla作为p ...
- Feign 客户端源码解析
Feign的使用非常简单,增加如下配置之后,便可以使用Feign进行调用.非常简单是不是.主要的工作由Feign框架完成.业务代码只提供了一个Interface, 然后由Feign动态生成代理类来实现 ...
- Spring Cloud系列(四):Eureka源码解析之客户端
一.自动装配 1.根据自动装配原理(详见:Spring Boot系列(二):Spring Boot自动装配原理解析),找到spring-cloud-netflix-eureka-client.jar的 ...
- 第零章 dubbo源码解析目录
第一章 第一个dubbo项目 第二章 dubbo内核之spi源码解析 2.1 jdk-spi的实现原理 2.2 dubbo-spi源码解析 第三章 dubbo内核之ioc源码解析 第四章 dubb ...
- Netty5服务端源码解析
Netty5源码解析 今天让我来总结下netty5的服务端代码. 服务端(ServerBootstrap) 示例代码如下: import io.netty.bootstrap.ServerBootst ...
- Fabric1.4源码解析:客户端安装链码
看了看客户端安装链码的部分,感觉还是比较简单的,所以在这里记录一下. 还是先给出安装链码所使用的命令好了,这里就使用官方的安装链码的一个例子: #-n 指定mycc是由用户定义 ...
- Netty源码解析—客户端启动
Netty源码解析-客户端启动 Bootstrap示例 public final class EchoClient { static final boolean SSL = System.getPro ...
- HDFS源码解析:教你用HDFS客户端写数据
摘要:终于开始了这个很感兴趣但是一直觉得困难重重的源码解析工作,也算是一个好的开端. 本文分享自华为云社区<hdfs源码解析之客户端写数据>,作者: dayu_dls. 在我们客户端写数据 ...
- jQuery2.x源码解析(构建篇)
jQuery2.x源码解析(构建篇) jQuery2.x源码解析(设计篇) jQuery2.x源码解析(回调篇) jQuery2.x源码解析(缓存篇) 笔者阅读了园友艾伦 Aaron的系列博客< ...
随机推荐
- The 19th Zhejiang University Programming Contest - H
Princess Cjb is caught by Heltion again! Her knights Little Sub and Little Potato are going to Helti ...
- Django web编程3 -- 创建用户账户
我们将建立一个用户注册和身份验证系统,让用户能够注册账户,进而登录和注销.我们将创建一个新的应用程序,其中包含与处理用户账户相关的所有功能.我们还将对模型Topic 稍做修改,让每个主题都归属于特定用 ...
- JS基础-第1天
JavaScript 第一天笔记 学习目标 了解Javascript的作用及其组成 掌握变量的使用,知道变量的作用是存储数据 掌握变量的命名规范 掌握 JavaScript 的 5 种简单数据类型 掌 ...
- CH4INRULZ从渗透到提权
下载了镜像后查看了ip http://192.168.16.128/ 然后用nmap扫描了一波 sudo nmap -vv -sV 192.168.16.128 访问80端口发现是个个人博客 访问80 ...
- 运维笔记-----nginx反向代理
在/opt/nginx 下的配置文件同级建立反向代理的配置文件manager.conf <span style="font-size:18px;">user nobod ...
- python setuptools
在安装python依赖库时,我们使用pip install 或者python setup.py install. pip 会自己搜索适合的版本,python setup.py 需要下载源码本地安装.但 ...
- Nodejs一键实现微信内打开网页url自动跳转外部浏览器访问的功能
前言 现如今微信对第三方推广链接的审核是越来越严格了,域名在微信中分享转发经常会被拦截,一旦被拦截用户就只能复制链接手动打开浏览器粘贴才能访问,要不然就是换个域名再推,周而复始.无论是哪一种情况都会面 ...
- Convolutional Pose Machines(理解)
0 - 背景 人体姿态识别存在遮挡以及关键点不清晰等主要挑战,然而,人体的关键点之间由于人体结构而具有相互关系,利用容易识别的关键点来指导难以识别关键点的检测,是提高关键点检测的一个思路.本文通过提出 ...
- springboot中使用kindeditor富文本编辑器实现博客功能
kindeditor在之前已经用过,现在在springboot项目中使用.并且也在里面使用了图片上传以及回显等功能. 其实主要的功能是图片的处理:kindeditor对输入的内容会作为html标签处理 ...
- 搜索表字段包含某字符串的SQL和监控Oracle数据库的SQL。
1.第一个SQL 背景:需要找到SQL Server数据库中,包含某个字符串的表,输出表和包含该字符串的列. )='=' --这里填要搜索的字符串 DECLARE @sql NVARCHAR(MAX) ...