Evenloop + scheduleAtFixedRate定时任务
public static void main(String[] args) {
EventLoopGroup group = new NioEventLoopGroup(2);
//会轮询使用1,2个线程。
System.out.println(group.next());
System.out.println(group.next());
System.out.println(group.next());
System.out.println(group.next());
EventLoop next = group.next();
//执行普通任务
next.next().submit(() ->{
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.print(next+":");
System.out.println("task01");
});
//定时任务
//Runnaerable,initialDelay,period,时间单位TimeUnit
group.next().scheduleAtFixedRate(()->{
System.out.println("good");
},0,5, TimeUnit.SECONDS);
System.out.println("main thread");
}
NettyServer:
package com.example.demo.tcpserver;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
public class HelloServer {
public static void main(String[] args) {
//1.服务器的启动器,负责组装netty组件
new ServerBootstrap()
//组件1 BossEventLoop可连接 WokerEventLoop可读事件(selector,thread)
//注意这里启动后这里进行监听Accept
.group(new NioEventLoopGroup())
//组件2 这里选择了NIO的实现
.channel(NioServerSocketChannel.class)
//组件3 worker(child) 负责处理读写哪些逻辑操作(hanler)
.childHandler(
//初始化器,负责添加一些handler
new ChannelInitializer<NioSocketChannel>() {
//通过重写initchannel方法添加具体 handler
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
//字节流转为String
//这里也注意了,这里是建立连接后,也就是Accept后才会执行
nioSocketChannel.pipeline().addLast(new StringDecoder());
nioSocketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter(){
//这里实际上有具体read方法 和抽象read0方法
/*
* 在项目中是重写了read0,为啥不是用这里的read
* 感觉是随意,源码是read调read0
* */
/*
* 读事件
* 参数: Obj:msg为上面StringDecode得到的String
*
* */
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
System.out.println(msg);
}
});
}
})
.bind(8080); //服务器启动后监听的端口
}
}
ClientServer:
package com.example.demo.client;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import java.net.InetSocketAddress;
public class HelloClient {
public static void main(String[] args) throws InterruptedException {
new Bootstrap()
.group(new NioEventLoopGroup())
.channel(NioSocketChannel.class)
.handler(new ChannelInitializer<NioSocketChannel>() {
//连接建立后被调用
@Override
protected void initChannel(NioSocketChannel nioSocketChannel) throws Exception {
nioSocketChannel.pipeline().addLast(new StringEncoder());
}
})
//连接到服务器
.connect(new InetSocketAddress("127.0.0.1",8080))
.sync()
.channel()
.writeAndFlush("hello world");
}
}