alielie
2026-06-04 771a0e7b6b1276087515bbe94de28358cb92963b
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
242
243
244
245
246
247
248
249
250
251
252
253
254
using System;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConnectionUtil
{
    /// <summary>
    /// TCP客户端包装类
    /// </summary>
    /// <summary>
    /// TCP客户端包装类
    /// </summary>
    public class TcpClientWrapper : IDisposable
    {
        private System.Net.Sockets.TcpClient _client;
        private NetworkStream _stream;
        private readonly string _host;
        private readonly int _port;
        private bool _isConnected;
        private readonly CancellationTokenSource _cts;
        private Task _heartbeatTask;
        private readonly SemaphoreSlim _sendReceiveLock;
 
        /// <summary>
        /// 初始化TCP客户端
        /// </summary>
        /// <param name="host">服务器地址</param>
        /// <param name="port">服务器端口</param>
        public TcpClientWrapper(string host = "127.0.0.1", int port = 6543)
        {
            _host = host;
            _port = port;
            _cts = new CancellationTokenSource();
            _sendReceiveLock = new SemaphoreSlim(1, 1);
        }
 
        /// <summary>
        /// 异步连接到服务器
        /// </summary>
        /// <returns>连接是否成功</returns>
        public async Task<bool> ConnectAsync()
        {
            try
            {
                _client = new System.Net.Sockets.TcpClient();
                await _client.ConnectAsync(_host, _port);
                _stream = _client.GetStream();
                _isConnected = true;
 
                // 启动心跳任务
                _heartbeatTask = StartHeartbeatAsync(_cts.Token);
 
                Console.WriteLine($"成功连接到服务器 {_host}:{_port}");
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接服务器失败:{ex.Message}");
                return false;
            }
        }
 
        /// <summary>
        /// 同步连接到服务器
        /// </summary>
        /// <returns>连接是否成功</returns>
        public bool Connect()
        {
            try
            {
                _client = new System.Net.Sockets.TcpClient();
                _client.Connect(_host, _port);
                _stream = _client.GetStream();
                _isConnected = true;
 
                // 启动心跳任务
                _heartbeatTask = StartHeartbeatAsync(_cts.Token);
                return true;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"连接服务器失败:{ex.Message}");
                return false;
            }
        }
 
        /// <summary>
        /// 启动心跳检测
        /// </summary>
        private async Task StartHeartbeatAsync(CancellationToken token)
        {
            while (!token.IsCancellationRequested && _isConnected)
            {
                try
                {
                    await Task.Delay(20000, token); // 20秒发送一次心跳
                    if (_isConnected)
                    {
                        await SendMessageAsync("ping");
                    }
                }
                catch (OperationCanceledException)
                {
                    break;
                }
                catch (Exception)
                {
                    _isConnected = false;
                    break;
                }
            }
        }
 
        /// <summary>
        /// 发送消息并接收响应
        /// </summary>
        /// <typeparam name="T">响应数据类型</typeparam>
        /// <param name="data">要发送的数据对象</param>
        /// <param name="timeout">超时时间</param>
        /// <returns>服务器响应数据</returns>
        public async Task<string> SendMessageAsync(string message, TimeSpan? timeout = null)
        {
            if (!_isConnected)
            {
                throw new InvalidOperationException("未连接到服务器");
            }
 
            TimeSpan actualTimeout = timeout ?? TimeSpan.FromSeconds(30);
 
            if (!await _sendReceiveLock.WaitAsync(actualTimeout))
            {
                throw new TimeoutException("等待发送超时");
            }
 
            try
            {
                byte[] messageBytes = Encoding.UTF8.GetBytes(message + "\r\n");
 
                // 发送消息
                await _stream.WriteAsync(messageBytes, 0, messageBytes.Length);
 
                // 接收响应
                byte[] buffer = new byte[1024];
                StringBuilder response = new StringBuilder();
                int bytesRead;
 
                CancellationTokenSource cts = new CancellationTokenSource(actualTimeout);
 
                try
                {
                    // 读取直到遇到换行符
                    while ((bytesRead = await _stream.ReadAsync(buffer, 0, buffer.Length)) > 0)
                    {
                        string received = Encoding.UTF8.GetString(buffer, 0, bytesRead);
                        response.Append(received);
 
                        if (received.EndsWith("\r\n"))
                        {
                            break;
                        }
 
                        if (cts.Token.IsCancellationRequested)
                        {
                            throw new TimeoutException("接收响应超时");
                        }
                    }
                }
                finally
                {
                    cts.Dispose();
                }
 
                string jsonResponse = response.ToString().TrimEnd('\r', '\n');
                Console.WriteLine($"收到服务器响应:{jsonResponse}");
 
                // 反序列化响应
                return jsonResponse;
            }
            catch (Exception ex)
            {
                Console.WriteLine($"发送消息失败:{ex.Message}");
                _isConnected = false;
                throw;
            }
            finally
            {
                _sendReceiveLock.Release();
            }
        }
 
        /// <summary>
        /// 同步发送消息并接收响应
        /// </summary>
        /// <typeparam name="T">响应数据类型</typeparam>
        /// <param name="data">要发送的数据对象</param>
        /// <param name="timeout">超时时间</param>
        /// <returns>服务器响应数据</returns>
        public string SendMessage(string message, TimeSpan? timeout = null)
        {
            timeout = timeout ?? TimeSpan.FromSeconds(30);
 
            try
            {
                // 使用 Task.Run 来执行异步操作,并等待结果
                return Task.Run(() => SendMessageAsync(message, timeout)).Result;
            }
            catch (AggregateException ae)
            {
                // 解包异常
                throw ae.InnerException;
            }
        }
 
        /// <summary>
        /// 检查是否已连接
        /// </summary>
        public bool IsConnected
        {
            get { return _isConnected; }
        }
 
        /// <summary>
        /// 释放资源
        /// </summary>
        public void Dispose()
        {
            _cts.Cancel();
            _isConnected = false;
            if (_stream != null)
            {
                _stream.Dispose();
            }
            if (_client != null)
            {
                _client.Dispose();
            }
            _cts.Dispose();
            if (_sendReceiveLock != null)
            {
                _sendReceiveLock.Dispose();
            }
        }
 
        /// <summary>
        /// 关闭连接
        /// </summary>
        public void Close()
        {
            Dispose();
        }
    }
}