‘liusuyi’
2023-12-28 eae9c75f70004dfe128718c63fe04c1a5cc35b01
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
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<String, BootNettyClientChannel> 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;
                }
            }
        }
 
    }
}