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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
// TcpServer.java
package home;
 
import java.io.*;
import java.net.BindException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
 
public class TcpServer extends NetworkBase {
    private ServerSocket serverSocket;
    private ExecutorService acceptorThread;
    private ConcurrentHashMap<String, ClientHandler> clients = new ConcurrentHashMap<>();
    private ClientListListener clientListListener;
 
    public interface ClientListListener {
        void onClientListChanged(java.util.List<String> clients);
    }
 
    public void setClientListListener(ClientListListener listener) {
        this.clientListListener = listener;
    }
 
    public TcpServer(String host, int port) {
        this.host = host;
        this.port = port;
    }
 
    @Override
    public boolean start() throws Exception {
        try {
            InetAddress localAddress = InetAddress.getByName(host);
            serverSocket = new ServerSocket(port, 50, localAddress);
 
            isRunning.set(true);
            startAcceptor();
            notifyStatus("TCP服务器已启动 - " + host + ":" + port, true);
            return true;
 
        } catch (BindException e) {
            notifyError("端口 " + port + " 被占用,请选择其他端口");
            return false;
        } catch (Exception e) {
            notifyError("启动TCP服务器失败: " + e.getMessage());
            return false;
        }
    }
 
    @Override
    public void stop() {
        isRunning.set(false);
        try {
            for (ClientHandler client : clients.values()) {
                client.stop();
            }
            clients.clear();
            updateClientList();
 
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (Exception e) {
            // 忽略关闭时的异常
        }
        if (acceptorThread != null) {
            acceptorThread.shutdownNow();
        }
        notifyStatus("TCP服务器已停止", false);
    }
 
    @Override
    public boolean sendData(String data) throws Exception {
        // TCP服务器可以向所有客户端或特定客户端发送数据
        // 这里简单实现向所有客户端发送
        boolean sent = false;
        for (ClientHandler client : clients.values()) {
            if (client.sendData(data)) {
                sent = true;
            }
        }
        return sent;
    }
 
    /**
     * 发送字节数据到所有客户端
     */
    public boolean sendData(byte[] data) throws Exception {
        boolean sent = false;
        for (ClientHandler client : clients.values()) {
            if (client.sendData(data)) {
                sent = true;
            }
        }
        return sent;
    }
 
    /**
     * 发送字节数据到特定客户端
     */
    public boolean sendDataToClient(String clientKey, byte[] data) throws Exception {
        ClientHandler client = clients.get(clientKey);
        if (client != null) {
            return client.sendData(data);
        }
        return false;
    }
 
    @Override
    public boolean isConnected() {
        return isRunning.get() && serverSocket != null && !serverSocket.isClosed();
    }
 
    private void startAcceptor() {
        acceptorThread = Executors.newSingleThreadExecutor();
        acceptorThread.execute(() -> {
            while (isRunning.get() && serverSocket != null && !serverSocket.isClosed()) {
                try {
                    Socket clientSocket = serverSocket.accept();
                    ClientHandler clientHandler = new ClientHandler(clientSocket);
                    String clientKey = clientSocket.getInetAddress().getHostAddress() + ":" + clientSocket.getPort();
                    clients.put(clientKey, clientHandler);
                    updateClientList();
                    notifyStatus("客户端连接: " + clientKey, true);
 
                } catch (Exception e) {
                    if (isRunning.get()) {
                        notifyError("接受客户端连接错误: " + e.getMessage());
                    }
                }
            }
        });
    }
 
    private void updateClientList() {
        if (clientListListener != null) {
            clientListListener.onClientListChanged(new java.util.ArrayList<>(clients.keySet()));
        }
    }
 
    private class ClientHandler {
        private Socket socket;
        private OutputStream outputStream;
        private InputStream inputStream;
        private ExecutorService receiverThread;
        private AtomicBoolean running = new AtomicBoolean(true);
 
        public ClientHandler(Socket socket) throws Exception {
            this.socket = socket;
            this.outputStream = socket.getOutputStream();
            this.inputStream = socket.getInputStream();
            startReceiver();
        }
 
        public boolean sendData(String data) {
            if (outputStream != null && !socket.isClosed()) {
                try {
                    outputStream.write(data.getBytes());
                    outputStream.flush();
                    return true;
                } catch (IOException e) {
                    return false;
                }
            }
            return false;
        }
 
        public boolean sendData(byte[] data) {
            if (outputStream != null && !socket.isClosed()) {
                try {
                    outputStream.write(data);
                    outputStream.flush();
                    return true;
                } catch (IOException e) {
                    return false;
                }
            }
            return false;
        }
 
        public void stop() {
            running.set(false);
            try {
                if (outputStream != null) outputStream.close();
                if (inputStream != null) inputStream.close();
                if (socket != null) socket.close();
            } catch (Exception e) {
                // 忽略关闭时的异常
            }
            if (receiverThread != null) {
                receiverThread.shutdownNow();
            }
        }
 
        private void startReceiver() {
            receiverThread = Executors.newSingleThreadExecutor();
            receiverThread.execute(() -> {
                byte[] buffer = new byte[1024];
                while (running.get() && socket != null && !socket.isClosed()) {
                    try {
                        int bytesRead = inputStream.read(buffer);
                        if (bytesRead > 0) {
                            byte[] receivedData = new byte[bytesRead];
                            System.arraycopy(buffer, 0, receivedData, 0, bytesRead);
                            String fromAddress = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
 
                            // 调用新的字节数组版本的notifyData方法
                            notifyData(receivedData, fromAddress);
                        } else if (bytesRead == -1) {
                            // 客户端断开连接
                            break;
                        }
                    } catch (IOException e) {
                        if (running.get()) {
                            // 客户端连接错误
                            break;
                        }
                    }
                }
 
                // 清理客户端
                String clientKey = socket.getInetAddress().getHostAddress() + ":" + socket.getPort();
                clients.remove(clientKey);
                updateClientList();
                notifyStatus("客户端断开: " + clientKey, false);
            });
        }
    }
 
    /**
     * 通知数据接收(字节数组版本)
     */
    protected void notifyData(byte[] data, String fromAddress) {
        if (dataListener != null) {
            dataListener.onDataReceived(data, fromAddress);
        }
    }
}