示例
以netty中提供的example程序为例
public static void main(String[] args) throws Exception {
// 创建boss线程组,用来初始化boss线程池,负责接收客户端连接
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
// 创建worker线程组,用来初始化worker线程池,负责处理boss分配过来的channel中的read事件,处理完后write给客户端
EventLoopGroup workerGroup = new NioEventLoopGroup();
final EchoServerHandler serverHandler = new EchoServerHandler();
try {
// ServerBootstrap直接翻译以下就可以理解 ---- 服务端引导程序
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) //通过反射创建出NioServerSocketChannel
.option(ChannelOption.SO_BACKLOG, 100) //配置boss相关属性
.childOption(ChannelOption.TCP_NODELAY, true) //配置worker相关属性
.handler(new LoggingHandler(LogLevel.INFO)) //配置boss业务处理handler(启动时执行)
.childHandler(new ChannelInitializer<SocketChannel>() { //配置worker业务处理handler(每次处理read/write等事件时都会执行)
@Override
public void initChannel(SocketChannel ch) throws Exception {
ChannelPipeline p = ch.pipeline();
p.addLast(new LoggingHandler(LogLevel.INFO));
p.addLast(serverHandler);
}
});
// 绑定端口,启动服务端
ChannelFuture f = b.bind(PORT).sync();
// Wait until the server socket is closed.
f.channel().closeFuture().sync();
} finally {
// Shut down all event loops to terminate all threads.
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
- 创建boss线程组和worker线程组
- 通过ServerBootstrap进行相关配置
- 绑定端口启动
服务端启动概述

整体大致分为如下4步:
1、创建服务端Channel:调用jdkapi,创建一个jdk的channel,然后包装成netty自己的channel,同时创建一些基本组件绑定在channel上
2、初始化服务端Channel:初始化一些基本属性,添加一些逻辑处理器
3、注册selector: 将jdk底层的channel注册到事件轮询器selector上,并把netty的服务端channel绑定在jdkchannel的attachment上,以便在后续轮询到事件时就可以拿到服务端channel
4、绑定端口:调用jdk底层api绑定端口,实现对该端口的监听
下一节会对这4步进行详细讲解
网友评论