package com.ard.utils.netty.tcp; import com.ard.utils.util.ByteUtils; import io.netty.buffer.ByteBuf; import io.netty.buffer.Unpooled; import org.springframework.scheduling.annotation.EnableScheduling; import org.springframework.scheduling.annotation.Scheduled; import org.springframework.stereotype.Component; import javax.xml.bind.DatatypeConverter; import java.util.Map; @Component @EnableScheduling public class ClientHelper { // 使用定时器发送心跳 @Scheduled(cron = "0/3 * * * * ?") public void heart_timer() { //System.err.println("BootNettyClientChannelCache.channelMapCache.size():" + BootNettyClientChannelCache.channelMapCache.size()); if (BootNettyClientChannelCache.channelMapCache.size() > 0) { for (Map.Entry entry : BootNettyClientChannelCache.channelMapCache.entrySet()) { BootNettyClientChannel bootNettyChannel = entry.getValue(); //System.out.println(bootNettyChannel.getCode()); try { byte[] header = {0x01, 0x02, 0x01}; byte[] payload = {0x10, 0x00, 0x00, 0x00}; byte[] payloadCrc32 = ByteUtils.parseCrc32(payload); byte[] footer = {0x01, 0x02, 0x00}; byte[] heart = ByteUtils.appendArrays(header, payload, payloadCrc32, footer); // log.debug("发送心跳:" + hexString); //message.writeBytes(heart); bootNettyChannel.getChannel().writeAndFlush(Unpooled.buffer().writeBytes(heart)); } catch (Exception e) { continue; } } } } }