刚接触Netty,写的不好敬请谅解。
最近有一个需求,需要从客户端客户端定时的向服务器发送数据,通知服务器自己的一些状态信息,比如本地的cup使用率,内存使用率等信息,大体实现如下:
是用到了java提供的线程池,newScheduledThreadPool:定长线程池,支持定时及周期性任务执行。
TestTask.java:
public class TestTask implements Runnable {
private final ChannelHandlerContext ctx;
public TestTask(ChannelHandlerContext ctx) {
this.ctx = ctx;
}
@Override
public void run() {
//do something
ctx.writeAndFlush(Unpooled.copiedBuffer(String.valueOf(System.currentTimeMillis()), CharsetUtil.UTF_8));
}
}
此类中的run方法可以执行其他的业务操作。
此处是客户端需要向服务器发送定时数据,故:
NettyClientHandler:
public class NettyClientHandler extends SimpleChannelInboundHandler<ByteBuf> {
private ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
private ScheduledFuture<?> heartBeat;
@Override
public void channelActive(ChannelHandlerContext ctx) {
this.heartBeat = this.scheduler.scheduleWithFixedDelay(new TestTask(ctx),0,2,TimeUnit.SECONDS);
}
@Override
public void channelInactive(ChannelHandlerContext ctx) throws Exception {
System.out.println("channelInactive 连接断开了");
}
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
cause.printStackTrace();
ctx.close();
}
}
服务器代码常规处理即可,此处并没有证书认证之类的操作,故
this.heartBeat = this.scheduler.scheduleWithFixedDelay(new TestTask(ctx),0,2,TimeUnit.SECONDS);
写在了channelActive方法中,若需要证书认证的操作,则channelActive中做证书认证的操作,而定时任务的操作写在channelRead0方法中即可。
此处是客户端向服务器发送定时任务,若服务器向客户端发送定时任务,则做相应修改即可。
也可做一些心跳检测之类的业务操作。
————————————————
版权声明:本文为CSDN博主「小梦_人生如戏」的原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接及本声明。
原文链接:https://blog.csdn.net/yu532164710/article/details/83210940