Netty服务端启动demo
1、NettyServer服务端代码
package com.wwl.netty.server.demo;
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;
import io.netty.util.AttributeKey;
public final class NettyServer {
public static void main(String[] args) {
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workGroup)
.channel(NioServerSocketChannel.class)
.childOption(ChannelOption.TCP_NODELAY, true)
.childAttr(AttributeKey.newInstance("childAttr"), "childAttrValue")
.handler(new ServerHandler())
.childHandler(new ChannelInitializer<SocketChannel>() {
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//ch.pipeline().addLast();
// 这里可以添加ChannelHandler逻辑链
}
});
try {
ChannelFuture f = b.bind(8888).sync();
f.channel().closeFuture().sync();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
bossGroup.shutdownGracefully();
workGroup.shutdownGracefully();
}
}
}
代码详解:
(1)EventLoopGroup bossGroup = new NioEventLoopGroup(1);
这行代码相当于Socket IO编程模型中的Server中的线程:
(2)EventLoopGroup workGroup = new NioEventLoopGroup();
这行代码相当于Socket IO编程模型中的Client中的线程:
(3)ServerBootstrap b = new ServerBootstrap();
这行代码就相当于创建了一个辅助对象,没有任何逻辑处理:
(4)b.group(bossGroup, workGroup)
这行代码表示配置了Server线程和Client线程:
(5).channel(NioServerSocketChannel.class)
这行代码表示设置服务端的SocketChannel:
(6).childOption(ChannelOption.TCP_NODELAY, true)
这行代码表示设置每一个客户端连接TCP的基本属性:
(7).childAttr(AttributeKey.newInstance("childAttr"), "childAttrValue")
这行代码表示在创建客户端连接的时候,可以给它绑定一些基本的属性:
(8).handler(new ServerHandler())
这行代码表示设置服务端启动时候的逻辑: