alielie
2026-04-16 1afe548ac40cc7f975917ef9bf2e156595cf81f3
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
using System;
using System.Collections.Concurrent;
using System.IO;
using System.IO.Pipes;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
 
namespace ConnectionUtil
{
    public class PipeServer : IDisposable
    {
        private readonly string _pipeName;
        private readonly int _maxNumberOfServerInstances;
        private readonly CancellationTokenSource _cancellationTokenSource;
        private readonly ConcurrentDictionary<string, NamedPipeServerStream> _activeConnections;
        private bool _isDisposed;
 
        // 事件定义
        public event EventHandler<PipeDataEventArgs> OnData;
        public event EventHandler<PipeConnectionEventArgs> OnNewConnection;
        public event EventHandler<PipeConnectionEventArgs> OnClientDisconnected;
        public event EventHandler<PipeErrorEventArgs> OnError;
 
        public PipeServer(string pipeName, int maxNumberOfServerInstances = NamedPipeServerStream.MaxAllowedServerInstances)
        {
            _pipeName = pipeName;
            _maxNumberOfServerInstances = maxNumberOfServerInstances;
            _cancellationTokenSource = new CancellationTokenSource();
            _activeConnections = new ConcurrentDictionary<string, NamedPipeServerStream>();
        }
 
        public void Start()
        {
            Task.Run(() =>
            {
                try
                {
                    while (!_cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        var pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut,
                            _maxNumberOfServerInstances, PipeTransmissionMode.Message);
                        try
                        {
                            pipeServer.WaitForConnection();
 
                            // 生成唯一的连接ID
                            string connectionId = Guid.NewGuid().ToString();
                            _activeConnections.TryAdd(connectionId, pipeServer);
 
                            // 触发新连接事件
                            OnNewConnection?.Invoke(this, new PipeConnectionEventArgs(connectionId));
 
                            // 开始处理该连接的数据
                            HandleClient(connectionId, pipeServer);
                        }
                        catch (OperationCanceledException)
                        {
                            pipeServer.Dispose();
                            break;
                        }
                        catch (Exception ex)
                        {
                            pipeServer.Dispose();
                            OnError?.Invoke(this, new PipeErrorEventArgs("等待连接时发生错误", ex));
                        }
                    }
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(this, new PipeErrorEventArgs("服务器运行时发生错误", ex));
                }
 
            });
        }
 
        static string ReadMessage(PipeStream s)
        {
            MemoryStream ms = new MemoryStream();
            byte[] buffer = new byte[0x1000]; // Read in 4 KB blocks
            do
            {
                ms.Write(buffer, 0, s.Read(buffer, 0, buffer.Length));
            }
            while (!s.IsMessageComplete);
            return Encoding.UTF8.GetString(ms.ToArray());
        }
 
        private void HandleClient(string connectionId, NamedPipeServerStream pipeServer)
        {
            Task.Run(() =>
            {
                try
                {
                    while (pipeServer.IsConnected && !_cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        try
                        {
                            string message = ReadMessage(pipeServer);
                            if (string.IsNullOrEmpty(message))
                                continue;
                            Console.WriteLine(message);
                            if (message == "ping")
                            {
                                message = "pong";
                            }
                            else
                            {
                                message += "Response";
                            }
                            SendMessage(connectionId, message);
                        }
                        catch (Exception ex)
                        {
                            OnError?.Invoke(this, new PipeErrorEventArgs($"处理客户端 {connectionId} 数据时发生错误", ex));
                            break;
                        }
                    }
                }
                finally
                {
                    // 清理连接
                    _activeConnections.TryRemove(connectionId, out _);
                    pipeServer.Dispose();
 
                    // 触发断开连接事件
                    OnClientDisconnected?.Invoke(this, new PipeConnectionEventArgs(connectionId));
                }
            });
        }
 
        public void SendMessage(string connectionId, string message)
        {
            if (_activeConnections.TryGetValue(connectionId, out var pipeServer))
            {
                try
                {
                    var msg = Encoding.UTF8.GetBytes(message);
                    pipeServer.Write(msg, 0, msg.Length);
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(this, new PipeErrorEventArgs($"向客户端 {connectionId} 发送消息时发生错误", ex));
                }
            }
        }
 
 
        public async Task StartAsync()
        {
            try
            {
                while (!_cancellationTokenSource.Token.IsCancellationRequested)
                {
                    var pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut,
                        _maxNumberOfServerInstances, PipeTransmissionMode.Message);
 
                    try
                    {
                        await pipeServer.WaitForConnectionAsync(_cancellationTokenSource.Token);
 
                        // 生成唯一的连接ID
                        string connectionId = Guid.NewGuid().ToString();
                        _activeConnections.TryAdd(connectionId, pipeServer);
 
                        // 触发新连接事件
                        OnNewConnection?.Invoke(this, new PipeConnectionEventArgs(connectionId));
 
                        // 开始处理该连接的数据
                        _ = HandleClientAsync(connectionId, pipeServer);
                    }
                    catch (OperationCanceledException)
                    {
                        pipeServer.Dispose();
                        break;
                    }
                    catch (Exception ex)
                    {
                        pipeServer.Dispose();
                        OnError?.Invoke(this, new PipeErrorEventArgs("等待连接时发生错误", ex));
                    }
                }
            }
            catch (Exception ex)
            {
                OnError?.Invoke(this, new PipeErrorEventArgs("服务器运行时发生错误", ex));
            }
        }
 
        private async Task HandleClientAsync(string connectionId, NamedPipeServerStream pipeServer)
        {
            try
            {
                using (var reader = new StreamReader(pipeServer))
                using (var writer = new StreamWriter(pipeServer))
                {
                    writer.AutoFlush = true;
 
                    while (pipeServer.IsConnected && !_cancellationTokenSource.Token.IsCancellationRequested)
                    {
                        try
                        {
                            string message = await reader.ReadLineAsync();
                            if (string.IsNullOrEmpty(message))
                                continue;
 
                            // 触发数据接收事件
                            OnData?.Invoke(this, new PipeDataEventArgs(connectionId, message));
 
                            // 发送响应
                            await writer.WriteLineAsync($"服务器已收到消息: {message}");
                        }
                        catch (Exception ex)
                        {
                            OnError?.Invoke(this, new PipeErrorEventArgs($"处理客户端 {connectionId} 数据时发生错误", ex));
                            break;
                        }
                    }
                }
            }
            finally
            {
                // 清理连接
                _activeConnections.TryRemove(connectionId, out _);
                pipeServer.Dispose();
 
                // 触发断开连接事件
                OnClientDisconnected?.Invoke(this, new PipeConnectionEventArgs(connectionId));
            }
        }
 
        public async Task SendMessageAsync(string connectionId, string message)
        {
            if (_activeConnections.TryGetValue(connectionId, out var pipeServer))
            {
                try
                {
                    using (var writer = new StreamWriter(pipeServer))
                    {
                        writer.AutoFlush = true;
                        await writer.WriteLineAsync(message);
                    }
                }
                catch (Exception ex)
                {
                    OnError?.Invoke(this, new PipeErrorEventArgs($"向客户端 {connectionId} 发送消息时发生错误", ex));
                }
            }
        }
 
        public void Stop()
        {
            _cancellationTokenSource.Cancel();
        }
 
        public void Dispose()
        {
            if (!_isDisposed)
            {
                Stop();
                foreach (var connection in _activeConnections.Values)
                {
                    connection.Dispose();
                }
                _activeConnections.Clear();
                _cancellationTokenSource.Dispose();
                _isDisposed = true;
            }
        }
    }
 
    public class PipeDataEventArgs : EventArgs
    {
        public string ConnectionId { get; }
        public string Data { get; }
 
        public PipeDataEventArgs(string connectionId, string data)
        {
            ConnectionId = connectionId;
            Data = data;
        }
    }
 
    public class PipeConnectionEventArgs : EventArgs
    {
        public string ConnectionId { get; }
 
        public PipeConnectionEventArgs(string connectionId)
        {
            ConnectionId = connectionId;
        }
    }
 
    public class PipeErrorEventArgs : EventArgs
    {
        public string Message { get; }
        public Exception Exception { get; }
 
        public PipeErrorEventArgs(string message, Exception exception)
        {
            Message = message;
            Exception = exception;
        }
    }
 
    public class StreamString
    {
        private Stream ioStream;
        private UnicodeEncoding streamEncoding;
 
        public StreamString(Stream ioStream)
        {
            this.ioStream = ioStream;
            streamEncoding = new UnicodeEncoding();
        }
 
        public string ReadString()
        {
            int len = 0;
 
 
            len = ioStream.ReadByte() * 256;
            len += ioStream.ReadByte();
            byte[] inBuffer = new byte[len];
            ioStream.Read(inBuffer, 0, len);
 
            return streamEncoding.GetString(inBuffer);
        }
 
        public int WriteString(string outString)
        {
            byte[] outBuffer = streamEncoding.GetBytes(outString);
            int len = outBuffer.Length;
            if (len > UInt16.MaxValue)
            {
                len = (int)UInt16.MaxValue;
            }
            ioStream.WriteByte((byte)(len / 256));
            ioStream.WriteByte((byte)(len & 255));
            ioStream.Write(outBuffer, 0, len);
            ioStream.Flush();
 
            return outBuffer.Length + 2;
        }
    }
 
}