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/PipeServer2.cs |  192 ++++++++++++++++++++++++++++++++++++++++++++++++
 1 files changed, 192 insertions(+), 0 deletions(-)

diff --git a/ConnectionUtil/PipeServer2.cs b/ConnectionUtil/PipeServer2.cs
new file mode 100644
index 0000000..cefbd5f
--- /dev/null
+++ b/ConnectionUtil/PipeServer2.cs
@@ -0,0 +1,192 @@
+锘縰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 static class PipeStreamUtil
+    {
+        public static string ReadMessage(this PipeStream ps)
+        {
+
+            MemoryStream ms = new MemoryStream();
+            byte[] buffer = new byte[0x1000];
+            do
+            {
+                ms.Write(buffer, 0, ps.Read(buffer, 0, buffer.Length));
+            }
+            while (!ps.IsMessageComplete);
+            return Encoding.UTF8.GetString(ms.ToArray());
+        }
+
+        public static void WriteMessage(this PipeStream ps, string message)
+        {
+            var msg = Encoding.UTF8.GetBytes(message);
+            ps.Write(msg, 0, msg.Length);
+            ps.Flush();
+        }
+    }
+
+    public class PipeServer2 : IDisposable
+    {
+        private readonly string _pipeName;
+        private readonly int _maxNumberOfServerInstances;
+        private readonly CancellationTokenSource _cancellationTokenSource;
+        private readonly ConcurrentDictionary<string, NamedPipeServerStream> _activeConnections;
+        private readonly ReaderWriterLockSlim _lock;
+        private bool _isDisposed;
+        private bool _isRunning;
+
+        // 浜嬩欢瀹氫箟
+        public event EventHandler<PipeDataEventArgs> OnData;
+        public event EventHandler<PipeConnectionEventArgs> OnClientConnected;
+        public event EventHandler<PipeConnectionEventArgs> OnClientDisconnected;
+        public event EventHandler<PipeErrorEventArgs> OnError;
+
+        public PipeServer2(string pipeName, int maxNumberOfServerInstances = 254)
+        {
+            _pipeName = pipeName;
+            _maxNumberOfServerInstances = maxNumberOfServerInstances;
+            _cancellationTokenSource = new CancellationTokenSource();
+            _activeConnections = new ConcurrentDictionary<string, NamedPipeServerStream>();
+            _lock = new ReaderWriterLockSlim();
+        }
+
+        public void Start()
+        {
+            if (_isRunning)
+                return;
+
+            _isRunning = true;
+
+            Task.Run(() =>
+            {
+                while (_isRunning && !_cancellationTokenSource.Token.IsCancellationRequested)
+                {
+                    try
+                    {
+                        var pipeServer = new NamedPipeServerStream(_pipeName, PipeDirection.InOut, _maxNumberOfServerInstances
+                            , PipeTransmissionMode.Message);
+                        pipeServer.WaitForConnection();
+
+                        string clientId = Guid.NewGuid().ToString();
+                        if (_activeConnections.TryAdd(clientId, pipeServer))
+                        {
+                            // 鍚姩澶勭悊瀹㈡埛绔秷鎭殑绾跨▼
+                            Thread clientThread = new Thread(() => HandleClient(clientId, pipeServer));
+                            clientThread.Start();
+
+                            OnClientConnected?.Invoke(this, new PipeConnectionEventArgs(clientId));
+                        }
+                    }
+                    catch (Exception ex)
+                    {
+                        OnError?.Invoke(this, new PipeErrorEventArgs("Connect", ex));
+                        Thread.Sleep(1000); // 鍙戠敓閿欒鏃剁瓑寰呬竴绉掑啀閲嶈瘯
+                    }
+                }
+            });
+        }
+
+
+
+        private void HandleClient(string clientId, NamedPipeServerStream pipeServer)
+        {
+            try
+            {
+                while (!_cancellationTokenSource.Token.IsCancellationRequested)
+                {
+                    try
+                    {
+                        // 绛夊緟瀹㈡埛绔彂閫佹秷鎭�
+                        string message = pipeServer.ReadMessage();
+                        if (string.IsNullOrEmpty(message))
+                            break;
+
+                        OnData?.Invoke(this, new PipeDataEventArgs(clientId, message));
+                    }
+                    catch (Exception ex)
+                    {
+                        OnError?.Invoke(this, new PipeErrorEventArgs("HandleClientMessageError", ex));
+                        break;
+                    }
+                }
+            }
+            finally
+            {
+                if (_activeConnections.TryRemove(clientId, out var pipe))
+                {
+                    pipe.Dispose();
+                }
+                OnClientDisconnected?.Invoke(this, new PipeConnectionEventArgs(clientId));
+            }
+        }
+
+        public void SendMessage(string clientId, string message)
+        {
+            if (!_activeConnections.TryGetValue(clientId, out var pipeServer))
+            {
+                throw new InvalidOperationException($"鎵句笉鍒板鎴风 {clientId}");
+            }
+
+            _lock.EnterWriteLock();
+            try
+            {
+                try
+                {
+                    pipeServer.WriteMessage(message);
+                }
+                catch (Exception ex)
+                {
+                    OnError?.Invoke(this, new PipeErrorEventArgs($"鍚戝鎴风 {clientId} 鍙戦�佹秷鎭椂鍙戠敓閿欒", ex));
+                }
+            }
+            finally
+            {
+                _lock.ExitWriteLock();
+            }
+        }
+
+        public void BroadcastMessage(string message)
+        {
+            _lock.EnterWriteLock();
+            try
+            {
+                foreach (var pipeServer in _activeConnections.Values)
+                {
+                    pipeServer.WriteMessage(message);
+                }
+            }
+            finally
+            {
+                _lock.ExitWriteLock();
+            }
+        }
+
+        public void Stop()
+        {
+            _isRunning = false;
+            _cancellationTokenSource.Cancel();
+        }
+
+        public void Dispose()
+        {
+            if (!_isDisposed)
+            {
+                Stop();
+                foreach (var pipeServer in _activeConnections.Values)
+                {
+                    pipeServer.Dispose();
+                }
+                _activeConnections.Clear();
+                _cancellationTokenSource.Dispose();
+                _lock.Dispose();
+                _isDisposed = true;
+            }
+        }
+    }
+}
\ No newline at end of file

--
Gitblit v1.9.1