ServerBootStrap是Netty服务端启动配置类,BootStrap是Netty客户端启动配置类。
//服务器端 Bootstrap serverBp = new Bootstrap();
group(bossGroup, workerGroup)
设置通讯模式,调用的是实现io.netty.channel.Channel接口的类。如:NioSocketChannel、NioServerSocketChannel,客户端一般选NioSocketChannel,服务端一般选NioServerSocketChannel。
option / handler / attr方法都定义在AbstractBootstrap中, 所以服务端和客户端的引导类方法调用都是调用的父类的对应方法。
我们先从一段代码入手:
EventLoopGroup group = new NioEventLoopGroup(); try { Bootstrap bootstrap = new Bootstrap(); bootstrap.group(group) .channel(NioSocketChannel.class) .option(ChannelOption.SO_KEEPALIVE, true) .handler(new ChannelInitializer<SocketChannel>() { @Override protected void initChannel(SocketChannel ch) throws Exception { //...... } }); //发起同步连接操作 ChannelFuture channelFuture = bootstrap.connect("localhost", 8080).sync(); channelFuture.channel().closeFuture().sync(); } catch (InterruptedException e) { e.printStackTrace(); }finally{ //关闭,释放线程资源 group.shutdownGracefully(); }
启动配置类Bootstrap 和 ServerBootstrap
原文:https://www.cnblogs.com/myitnews/p/12212807.html