package com.sgg.netty.taskQueue;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
/**
* @description:
* @date : 2020/6/7 18:23
* @author: zwz
*/
public class NettyServerScheduleTaskQueueAsync {
public static void main(String[] args) throws InterruptedException {
//创建BossGroup和WorkerGroup
//1. 创建两个线程组
//2. bossGroup只是处理连接请求,真正的和客户端业务处理,会交给workerGroupo完成
//3. 两个都是无限循环
//4. bossGroup 和 workGroup 含有的子线程的个数
//默认实际 CPU 核数*2=8。在不传参数的情况下有8个 线程。我的24个线程
EventLoopGroup bossGroup = new NioEventLoopGroup(1);
EventLoopGroup workerGroup = new NioEventLoopGroup();
//创建服务器端的启动对象,配置参数
ServerBootstrap bootstrap = new ServerBootstrap();
try {
//使用链式编程设置
bootstrap.group(bossGroup, workerGroup)
.channel(NioServerSocketChannel.class) //使用NioServerSocketChannel作为服务器的通道实现
.option(ChannelOption.SO_BACKLOG, 128) //设置线程队列的连接个数
.childHandler(new ChannelInitializer<SocketChannel>() { //创建一个通道测试对象-匿名对象
//给pipeline设置处理器
@Override
protected void initChannel(SocketChannel ch) throws Exception {
//可以使用一个集合管理socketChannel,再推送消息,可以将业务加入到各个
//channel对应的NIOEventLoop的taskQueue或者scheduleTaskQueue
System.out.println("客户SocketChannel hashCode=" + ch.hashCode());
ch.pipeline().addLast(new NettyServerScheduleTaskQueueHandler());
}
}); //给我们的 workerGroup 的EventLoop对应的管道设置处理器
System.out.println("服务器准好了");
//绑定一个端口并同步,生成一个 ChannelFuture 对象
//启动服务器
ChannelFuture channelFuture = bootstrap.bind(6668).sync();
//给ChannelFuture注册监听器,监控我们关心的事件
channelFuture.addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) throws Exception {
if (future.isSuccess()) {
System.out.println("监听端口成功");
} else {
System.out.println("监听端口失败");
}
}
});
//对关闭通道进行监听
channelFuture.channel().closeFuture().sync();
} finally {
bossGroup.shutdownGracefully();
workerGroup.shutdownGracefully();
}
}
}
网友评论