liusuyi
2025-10-17 f9ee3fa619d478e5e592dfaa99a5b993feb6c67a
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
42
package com.ard.work.component.netty;
 
import com.ard.work.component.netty.command.BaseCmd;
import com.ard.work.component.netty.cache.TyTcpServerCache;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import java.net.InetSocketAddress;
 
/**
 * Description:
 * Author: lsy
 * Date: 2025年10月17日14:27
 **/
@Slf4j
public class TcpClientUtil {
 
    /**
     * 向指定边缘服务器发送消息
     */
    public static void sendMessage(String serverId, BaseCmd msg) {
        try {
            Channel channel = TyTcpServerCache.getChannel(serverId);
            if (channel == null) {
                log.error("未找到边缘服务器 [{}] 的连接", serverId);
                return;
            }
 
            if (!channel.isActive()) {
                log.warn("边缘服务器 [{}] 连接未激活,无法发送消息", serverId);
                return;
            }
 
            InetSocketAddress remote = (InetSocketAddress) channel.remoteAddress();
            channel.writeAndFlush(msg);
            log.warn("→ 向边缘服务器 [{}] ({}:{}) 发送消息,命令码:0x{}",
                    serverId, remote.getHostString(), remote.getPort(),
                    String.format("%02X", msg.getCmdCode() & 0xFF));
        } catch (Exception e) {
            log.error("发送消息到边缘服务器 [{}] 异常:{}", serverId, e.getMessage());
        }
    }
}