From 9d1660270272180cd71147d6ddd53d1382643d2e Mon Sep 17 00:00:00 2001
From: wenxiangchao <wenxiangchao@ihengxin.com.cn>
Date: 星期一, 02 十一月 2026 18:00:14 +0800
Subject: [PATCH] merge: 并入远程 Initial commit 作为历史根节点

---
 ConnectionUtil/PipeServer.cs |  347 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 347 insertions(+), 0 deletions(-)

diff --git a/ConnectionUtil/PipeServer.cs b/ConnectionUtil/PipeServer.cs
new file mode 100644
index 0000000..90425df
--- /dev/null
+++ b/ConnectionUtil/PipeServer.cs
@@ -0,0 +1,347 @@
+锘縰sing 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();
+
+                            // 鐢熸垚鍞竴鐨勮繛鎺D
+                            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);
+
+                        // 鐢熸垚鍞竴鐨勮繛鎺D
+                        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;
+        }
+    }
+
+}
\ No newline at end of file

--
Gitblit v1.9.1