功能:实现客户端向服务端定时发消息。
public class MyClientHandler extends ChannelInboundHandlerAdapter {
/**
* 给服务端发送消息
* @param ctx
* @throws Exception
*/
@Override
public void channelActive(ChannelHandlerContext ctx) throws RejectedExecutionException {
ctx.channel().eventLoop().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
ctx.writeAndFlush(Unpooled.copiedBuffer("来自客户端的消息", CharsetUtil.UTF_8));
}
}, 1,3, TimeUnit.SECONDS);
}
---------------------省略其他方法-----------------------------
}
服务端接收的消息:

2、schedule的用法
ctx.channel().eventLoop().schedule(new Runnable() {
@Override
public void run() {

本文介绍了如何在Java中使用Netty框架实现在客户端和服务端之间的定时消息发送,重点讲解了`ChannelInboundHandler`和`scheduleAtFixedRate`方法的使用,以及`eventLoop`在定时任务中的作用。
最低0.47元/天 解锁文章
2756

被折叠的 条评论
为什么被折叠?



