alielie
7 天以前 e57938fbda9bff702004038f76d009422968bff5
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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
using DeviceService.Core;
using System.IO;
using System.IO.Pipes;
using System.Text.Json;
 
namespace DeviceService.Service.NamePipe
{
    /// <summary>
    /// 基于命名管道的服务端实现(Message 模式)。
    /// 启动后持续监听客户端连接,收到的每条消息通过 <see cref="DataReceived"/> 事件上抛,
    /// 并携带可回写数据的 <see cref="NamePipeClient"/> 实例。
    /// </summary>
    public class NamePipeService : IService, IDisposable
    {
        /// <summary>默认允许的最大管道实例数(即最大并发连接数)。</summary>
        public const int DefaultMaxInstances = 254;
 
        /// <summary>停止服务时等待后台任务结束的最长时间。</summary>
        private static readonly TimeSpan StopTimeout = TimeSpan.FromSeconds(3);
 
        private readonly string _pipeName;
        private readonly int _maxInstances;
        private readonly object _sync = new object();
        private readonly Dictionary<NamePipeClient, Task> _clients = new Dictionary<NamePipeClient, Task>();
 
        private CancellationTokenSource? _cts;
        private NamedPipeServerStream? _listenStream;
        private Task? _acceptTask;
        private bool _running;
        private bool _disposed;
 
        /// <param name="pipeName">管道名称,为空时在 Start 阶段校验失败。</param>
        /// <param name="maxInstances">最大并发连接数。</param>
        public NamePipeService(string? pipeName = null, int maxInstances = DefaultMaxInstances)
        {
            if (maxInstances <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(maxInstances), "最大实例数必须大于 0。");
            }
            _pipeName = pipeName ?? string.Empty;
            _maxInstances = maxInstances;
        }
        public event EventHandler<IClient>? ClientConnected;
        public event EventHandler<IClient>? ClientDisConnected;
        public event EventHandler<RequestArg>? DataReceived;
 
        /// <summary>管道名称。</summary>
        public string PipeName => _pipeName;
 
        /// <summary>服务是否处于监听状态。</summary>
        public bool IsRunning
        {
            get
            {
                lock (_sync)
                {
                    return _running;
                }
            }
        }
 
        /// <summary>当前已连接的客户端数量。</summary>
        public int ClientCount
        {
            get
            {
                lock (_sync)
                {
                    return _clients.Count;
                }
            }
        }
 
        public bool Start(out string msg)
        {
            lock (_sync)
            {
                if (_disposed)
                {
                    msg = "服务已释放,无法启动。";
                    return false;
                }
 
                if (_running)
                {
                    msg = "服务已处于运行状态。";
                    return false;
                }
 
                if (string.IsNullOrWhiteSpace(_pipeName))
                {
                    msg = "管道名称未设置,无法启动。";
                    return false;
                }
 
                NamedPipeServerStream listenStream;
                try
                {
                    listenStream = CreatePipeStream();
                }
                catch (Exception ex)
                {
                    msg = $"创建命名管道 \"{_pipeName}\" 失败:{ex.Message}";
                    return false;
                }
 
                var cts = new CancellationTokenSource();
                _cts = cts;
                _listenStream = listenStream;
                _running = true;
                _acceptTask = Task.Run(() => AcceptLoopAsync(listenStream, cts.Token));
            }
 
            msg = $"命名管道 \"{_pipeName}\" 已启动监听。";
            return true;
        }
 
        public bool Stop(out string msg)
        {
            Task? acceptTask;
            List<Task> clientTasks = new List<Task>();
 
            lock (_sync)
            {
                if (!_running)
                {
                    msg = "服务未运行。";
                    return false;
                }
 
                _running = false;
                acceptTask = _acceptTask;
                _acceptTask = null;
 
                try
                {
                    _cts?.Cancel();
                }
                catch
                {
                    // 忽略取消过程中的异常
                }
 
                try
                {
                    _listenStream?.Dispose();
                }
                catch
                {
                    // 忽略关闭监听流的异常
                }
 
                _listenStream = null;
 
                // 关闭所有客户端连接,使阻塞中的读取立即结束
                foreach (KeyValuePair<NamePipeClient, Task> item in _clients)
                {
                    try
                    {
                        item.Key.Dispose();
                    }
                    catch
                    {
                        // 忽略单个连接的关闭异常
                    }
 
                    clientTasks.Add(item.Value);
                }
 
                _clients.Clear();
 
                _cts?.Dispose();
                _cts = null;
            }
 
            try
            {
                acceptTask?.Wait(StopTimeout);
                if (clientTasks.Count > 0)
                {
                    Task.WaitAll(clientTasks.ToArray(), StopTimeout);
                }
            }
            catch (AggregateException)
            {
                // 后台任务在校验/取消阶段抛出的异常无需向上传播
            }
 
            msg = "服务已停止。";
            return true;
        }
 
        private NamedPipeServerStream CreatePipeStream()
        {
            var pipe = new NamedPipeServerStream(
                _pipeName,
                PipeDirection.InOut,
                _maxInstances,
                PipeTransmissionMode.Message,
                PipeOptions.Asynchronous);
            pipe.ReadMode = PipeTransmissionMode.Message;
            return pipe;
        }
 
        /// <summary>
        /// 连接接受循环:每接受一个连接就交给独立的处理任务,并准备下一个管道实例继续监听。
        /// </summary>
        private async Task AcceptLoopAsync(NamedPipeServerStream initial, CancellationToken token)
        {
            NamedPipeServerStream? listenStream = initial;
            try
            {
                while (!token.IsCancellationRequested)
                {
                    NamedPipeServerStream stream = listenStream!;
                    listenStream = null;
 
                    try
                    {
                        await stream.WaitForConnectionAsync(token).ConfigureAwait(false);
                    }
                    catch (OperationCanceledException)
                    {
                        stream.Dispose();
                        break;
                    }
                    catch (ObjectDisposedException)
                    {
                        break;
                    }
                    catch (IOException)
                    {
                        stream.Dispose();
                        break;
                    }
 
                    // .NET Framework 下 WaitForConnectionAsync 可能提前返回,此处校验连接确实建立
                    if (!stream.IsConnected)
                    {
                        try
                        {
                            await Task.Delay(50, token).ConfigureAwait(false);
                        }
                        catch (OperationCanceledException)
                        {
                            break;
                        }
 
                        listenStream = stream;
                        continue;
                    }
 
                    var client = new NamePipeClient(stream);
                    Task handler = Task.Run(() => HandleClientAsync(client, token));
                    RegisterClient(client, handler);
 
                    // 为下一个连接准备新的管道实例
                    try
                    {
                        listenStream = CreatePipeStream();
                    }
                    catch (Exception)
                    {
                        break;
                    }
 
                    lock (_sync)
                    {
                        if (!_running)
                        {
                            break;
                        }
 
                        _listenStream = listenStream;
                    }
                }
            }
            catch (Exception)
            {
                // 监听循环中的未知异常直接结束循环,由 Stop 负责收尾
            }
            finally
            {
                try
                {
                    listenStream?.Dispose();
                }
                catch
                {
                    // 忽略关闭异常
                }
 
                lock (_sync)
                {
                    _listenStream = null;
                }
            }
        }
 
        /// <summary>
        /// 单个连接的读取循环:按行读取消息并触发 <see cref="DataReceived"/>。
        /// </summary>
        private async Task HandleClientAsync(NamePipeClient client, CancellationToken token)
        {
            OnClientEvent(ClientConnected, client);
            try
            {
                while (!token.IsCancellationRequested)
                {
                    string? message = await client.ReadMessageAsync().ConfigureAwait(false);
                    if (message == null)
                    {
                        break;
                    }
 
                    RaiseDataReceived(client, message);
                }
            }
            catch (OperationCanceledException)
            {
                // 服务停止导致的正常取消
            }
            catch (Exception)
            {
                // 连接断开、数据非法等情况直接结束该连接的读取
            }
            finally
            {
                OnClientEvent(ClientDisConnected, client);
                UnregisterClient(client);
                client.Dispose();
            }
        }
 
        private void OnClientEvent(EventHandler<IClient>? handler, IClient client)
        {
            if (handler == null)
            {
                return;
            }
 
            try
            {
                handler(this, client);
            }
            catch
            {
                // 订阅方的异常不应影响连接的建立与释放
            }
        }
 
        private void RaiseDataReceived(NamePipeClient client, string raw)
        {
            var data = JsonSerializer.Deserialize<RequestData>(raw);
            var arg = new RequestArg
            {
                Data = data,
                Raw = raw,
                Client = client
            };
            OnDataReceived(arg);
        }
 
        private void RegisterClient(NamePipeClient client, Task handler)
        {
            lock (_sync)
            {
                if (_running)
                {
                    _clients[client] = handler;
                    return;
                }
            }
 
            // 服务正在停止,直接释放该连接
            client.Dispose();
        }
 
        private void UnregisterClient(NamePipeClient client)
        {
            lock (_sync)
            {
                _clients.Remove(client);
            }
        }
 
        private void OnDataReceived(RequestArg arg)
        {
            EventHandler<RequestArg>? handler = DataReceived;
            if (handler == null)
            {
                return;
            }
 
            try
            {
                handler?.Invoke(this, arg);
            }
            catch
            {
                // 订阅方的异常不应中断管道读取
            }
        }
 
        public void Dispose()
        {
            if (_disposed)
            {
                return;
            }
 
            try
            {
                Stop(out _);
            }
            catch
            {
                // 释放阶段的异常忽略
            }
 
            _disposed = true;
        }
    }
}