zsh_root
2025-12-10 8d662de2fd262b3a485f16e197cb4d0ca2a61cdf
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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
// NetworkBase.java - 网络通信基类
package home;
 
import java.io.IOException;
import java.net.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.function.Consumer;
 
public abstract class NetworkBase {
    protected AtomicBoolean isRunning = new AtomicBoolean(false);
    protected String host;
    protected int port;
    protected NetworkDataListener dataListener;
 
    // 新增:响应消费者,用于处理特定的响应数据
    protected Consumer<byte[]> responseConsumer;
 
    public interface NetworkDataListener {
        void onDataReceived(byte[] data, String fromAddress);
        void onStatusChanged(String status, boolean isConnected);
        void onError(String errorMessage);
    }
 
    public void setDataListener(NetworkDataListener listener) {
        this.dataListener = listener;
    }
 
    /**
     * 设置响应消费者 - 新增方法
     * 用于处理特定的响应数据,比如配置读取的响应
     */
    public void setResponseConsumer(Consumer<byte[]> consumer) {
        this.responseConsumer = consumer;
    }
 
    /**
     * 获取响应消费者 - 新增方法
     */
    public Consumer<byte[]> getResponseConsumer() {
        return responseConsumer;
    }
 
    /**
     * 通知响应数据 - 新增方法
     * 如果有设置响应消费者,将数据传递给消费者
     */
    protected void notifyResponseData(byte[] data) {
        if (responseConsumer != null) {
            responseConsumer.accept(data);
        }
    }
 
    /**
     * 处理接收到的数据 - 新增方法
     * 同时通知数据监听器和响应消费者
     */
    protected void handleReceivedData(byte[] data, String fromAddress) {
        // 通知数据监听器
        notifyData(data, fromAddress);
 
        // 通知响应消费者
        notifyResponseData(data);
    }
 
    public abstract boolean start() throws Exception;
    public abstract void stop();
    public abstract boolean sendData(String data) throws Exception;
    public abstract boolean isConnected();
 
    protected void notifyStatus(String status, boolean connected) {
        if (dataListener != null) {
            dataListener.onStatusChanged(status, connected);
        }
    }
 
    protected void notifyError(String error) {
        if (dataListener != null) {
            dataListener.onError(error);
        }
    }
 
    protected void notifyData(byte[] data, String fromAddress) {
        if (dataListener != null) {
            dataListener.onDataReceived(data, fromAddress);
        }
    }
 
    /**
     * 获取数据监听器
     */
    public NetworkDataListener getDataListener() {
        return dataListener;
    }
}