我使用netty版本是4.1.30.Final
,netty服务器任务是发送modbus命令请求设备数据时间表(1分钟)。
客户端程序有时会重复登录,然后通道不会关闭。之前的频道是不同的(它看起来设备保持多个频道)。我手动关闭前一个。但是期间任务正在进行。
Netty初始化代码
// group is final EventExecutorGroup group = new DefaultEventExecutor();
.addLast(group, serverDataPacketHandler);
检查重复频道。 deviceIdentity是客户端程序发送的唯一。
// loginChannels is Map<String, Channel>
if (loginChannels.containsKey(deviceIdentity) && loginChannels.get(deviceIdentity) !=
ctx.channel()) {
// close prev one.
logger.info("repeatedly login");
loginChannels.get(deviceIdentity).close();
loginChannels.put(deviceIdentity, ctx.channel());
} else {
loginChannels.put(deviceIdentity, ctx.channel());
}
当设备登录时
Channel channel = ctx.channel();
ctx.executor().scheduleAtFixedRate(new Runnable() {
@Override
public void run() {
logger.info("task start .......");
// send modbus command
channel.writeAndFlush("01 04 00 00 00 01 crc crc");
}, 0, 60, TimeUnit.SECONDS);
结果:
任务运行时间不是1分钟。当客户端重复登录时
由于EventExecutor
在不同的Channel
s中共享,因此它具有封闭频道的概念。如果你想不再运行它,你需要打电话给ScheduledFuture.cancel()
。