Shunnet 2 lat temu
rodzic
commit
e8be598d22

+ 24 - 15
src/YSAI.DAQ/YSAI.Core/communication/net/tcp/client/TcpClientOperate.cs

@@ -4,6 +4,7 @@ using System.IO.Ports;
 using System.Linq;
 using System.Net;
 using System.Net.Sockets;
+using System.Net.WebSockets;
 using System.Text;
 using System.Threading.Tasks;
 using YSAI.Core.data;
@@ -106,7 +107,7 @@ namespace YSAI.Core.communication.net.tcp.client
                             if (alen > 0)
                             {
                                 byte[] CacheBuffer = new byte[alen];
-                                int bytes = Communication.GetStream().Read(CacheBuffer, 0, alen);  //读取数据
+                                int bytes = Communication.GetStream().ReadAsync(CacheBuffer, 0, alen).WaitAsync(token.Token).Result;  //读取数据
                                 if (bytes > 0)
                                 {
                                     OnEventHandler(this, new EventResult(true, $"接收到[{ClassName}]监控数据", ByteTool.ByteTrimEnd(CacheBuffer), @enum.ResultType.Bytes));  //数据传递出去
@@ -115,22 +116,23 @@ namespace YSAI.Core.communication.net.tcp.client
                                 {
                                     OnEventHandler(this, new EventResult(false, $"接收到[{ClassName}]监控数据长度错误(小于等于零)"));  //数据传递出去
                                     OffAsync();
+                                    return;
                                 }
                             }
-                            else
-                            {
-                                Thread.Sleep(SleepTime);
-                            }
                         }
                         else
                         {
-                            Thread.Sleep(SleepTime);
+                            OnEventHandler(this, new EventResult(false, $"[{ClassName}]监控异常,与服务端断开连接"));
+                            OffAsync();
+                            return;
                         }
+                        Thread.Sleep(SleepTime);
                     }
                     catch (Exception ex)
                     {
                         OnEventHandler(this, new EventResult(false, $"[{ClassName}]监控异常,关闭对象:{ex.Message}"));
                         OffAsync();
+                        return;
                     }
                 }
             }, token.Token);
@@ -150,17 +152,21 @@ namespace YSAI.Core.communication.net.tcp.client
                 {
                     try
                     {
-                        if (!Communication.Connected)
+                        if (Communication == null || !Communication.Connected)
                         {
-                            if (On().State)
+                            Communication = new TcpClient();
+                            //设置参数
+                            IPEndPoint IpPort = new IPEndPoint(IPAddress.Parse(basics.Ip), basics.Port);
+                            Communication.SendTimeout = basics.Timeout;
+                            if (!Communication.ConnectAsync(IpPort).WaitAsync(new TimeSpan(0,0,0,0, basics.Timeout), token.Token).IsCanceled)
                             {
-                                OnEventHandler(this, new EventResult(true, $"[{ClassName}]断线重连成功"));  //数据传递出去
-                                ReconnectionCount = 1;
+                                OnEventHandler(this, new EventResult(false, $"[{ClassName}]断线重连失败,连接超时,重连{ReconnectionCount}次"));  //数据传递出去
+                                ReconnectionCount++;
                             }
                             else
                             {
-                                OnEventHandler(this, new EventResult(false, $"[{ClassName}]断线重连失败,重连{ReconnectionCount}次"));  //数据传递出去
-                                ReconnectionCount++;
+                                OnEventHandler(this, new EventResult(true, $"[{ClassName}]断线重连成功"));  //数据传递出去
+                                ReconnectionCount = 1;
                             }
                         }
                     }
@@ -237,7 +243,7 @@ namespace YSAI.Core.communication.net.tcp.client
             Depart("Off");
             try
             {
-                if (Communication != null && Communication.Connected)
+                if (Communication != null)
                 {
                     //关闭监控
                     if (MonitorSwitch != null)
@@ -287,8 +293,11 @@ namespace YSAI.Core.communication.net.tcp.client
             {
                 if (Communication != null && Communication.Connected)
                 {
-                    Communication.GetStream().Write(Data, 0, Data.Length);
-                    return Break("Send", true);
+                    if (Communication.GetStream().WriteAsync(Data, 0, Data.Length).Wait(basics.Timeout))
+                    {
+                        return Break("Send", true);
+                    }
+                    return Break("Send", false, "发送数据超时");
                 }
                 return Break("Send", false, "未连接");
             }

+ 41 - 29
src/YSAI.DAQ/YSAI.Core/communication/net/tcp/service/TcpServiceOperate.cs

@@ -113,7 +113,7 @@ namespace YSAI.Core.communication.net.tcp.service
                 {
                     try
                     {
-                        Socket socket = Communication.AcceptSocket(); // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字;
+                        Socket socket = Communication.AcceptSocketAsync().WaitAsync(token.Token).Result; // 一旦监听到一个客户端的请求,就返回一个与该客户端通信的 套接字;
                         string? IpPort = socket.RemoteEndPoint.ToString();
                         if (!ClientIoc.ContainsKey(IpPort))  //当字典中没有这个连接对象
                         {
@@ -150,21 +150,22 @@ namespace YSAI.Core.communication.net.tcp.service
             {
                 Socket ClientCon = socket as Socket;
                 string IpPort = ClientCon.RemoteEndPoint.ToString();
-                byte[] DataByte = new byte[1024 * 1024];  //数据缓冲区
+                ArraySegment<byte> DataByte = new ArraySegment<byte>(new byte[1024 * 1024]); //数据缓冲区
                 while (!token.IsCancellationRequested)
                 {
                     try
                     {
-                        int length = ClientCon.Receive(DataByte); // 接收数据,并返回数据的长度;
+                        int length = ClientCon.ReceiveAsync(DataByte,SocketFlags.Partial).WaitAsync(token.Token).Result; // 接收数据,并返回数据的长度;
                         if (length > 0)
                         {
-                            OnEventHandler(this, new EventResult(true, $"[{IpPort}]数据接收成功", new TcpServiceData.ClientMessage { Step = TcpServiceData.Steps.消息接收, IpPort = IpPort, Data = ByteTool.BytesDispose(DataByte, 0, DataByte.Length - length) }, @enum.ResultType.Bytes));
+                            OnEventHandler(this, new EventResult(true, $"[{IpPort}]数据接收成功", new TcpServiceData.ClientMessage { Step = TcpServiceData.Steps.消息接收, IpPort = IpPort, Data = ByteTool.ByteTrimEnd(DataByte.Array) }, @enum.ResultType.Bytes));
                         }
                         else
                         {
                             OnEventHandler(this, new EventResult(false, $"[{IpPort}]发来的数据长度错误(小于等于零),已强制关闭连接", new TcpServiceData.ClientMessage { Step = TcpServiceData.Steps.客户端断开, IpPort = IpPort }, @enum.ResultType.All));
                             //移除此客户端
                             RemoveAsync(IpPort);
+                            return;
                         }
                     }
                     catch (Exception ex)
@@ -172,6 +173,7 @@ namespace YSAI.Core.communication.net.tcp.service
                         OnEventHandler(this, new EventResult(false, $"监控[{IpPort}]消息异常:{ex.Message}", new TcpServiceData.ClientMessage { Step = TcpServiceData.Steps.客户端断开, IpPort = IpPort }, @enum.ResultType.All));
                         //移除此客户端
                         RemoveAsync(IpPort);
+                        return;
                     }
                 }
             }, token.Token);
@@ -241,13 +243,12 @@ namespace YSAI.Core.communication.net.tcp.service
                     }
                     //清空
                     ClientIoc.Clear();
-
                     Communication.Stop();
                     Communication = null;
 
                     return Break("Off", true);
                 }
-                return Break("Off", false, "未连接");
+                return Break("Off", false, "未启动");
             }
             catch (Exception ex)
             {
@@ -276,7 +277,7 @@ namespace YSAI.Core.communication.net.tcp.service
                     ClientIoc[IpPort].TaskObj.Wait();
                     ClientIoc[IpPort].SocketObj.Close();
                     ClientIoc[IpPort].SocketObj.Dispose();
-
+                    ClientIoc.Remove(IpPort, out _);
                     return Break("Remove", true);
                 }
                 return Break("Remove", false, "Ip Port 不存在");
@@ -292,7 +293,7 @@ namespace YSAI.Core.communication.net.tcp.service
         /// <returns></returns>
         public Task<OperateResult> RemoveAsync(string? Key)
         {
-            return Task.Run(() => RemoveAsync(Key));
+            return Task.Run(() => Remove(Key));
         }
         /// <summary>
         /// 数据发送
@@ -305,39 +306,50 @@ namespace YSAI.Core.communication.net.tcp.service
             Depart("Send");
             try
             {
-                List<string> Message=new List<string>();
-                if (string.IsNullOrEmpty(IpPort))
+                if (Communication != null)
                 {
-                    //群发
-                    foreach (var client in ClientIoc) 
+                    List<string> Message = new List<string>();
+                    if (string.IsNullOrEmpty(IpPort))
                     {
-                        if (client.Value.SocketObj.Send(Data) <= 0)
+                        if (ClientIoc.Count.Equals(0))
                         {
-                            Message.Add($"数据发送[{client.Value.SocketObj.RemoteEndPoint}]失败");
+                            return Break("Send", false, "客户端未连接");
+                        }
+                        //群发
+                        foreach (var client in ClientIoc)
+                        {
+                            if (client.Value.SocketObj.Send(Data) <= 0)
+                            {
+                                Message.Add($"数据发送[{client.Value.SocketObj.RemoteEndPoint}]失败");
+                            }
                         }
-                    }
 
-                    if (Message.Count > 0)
-                    {
-                        return Break("Send", false, "存在失败数据", Message, @enum.ResultType.All);
-                    }
-                }
-                else
-                {
-                    //指定发送
-                    if (ClientIoc.ContainsKey(IpPort))
-                    {
-                        if (ClientIoc[IpPort].SocketObj.Send(Data) <= 0)
+                        if (Message.Count > 0)
                         {
-                            return Break("Send", false, $"数据发送[{IpPort}]失败", Message, @enum.ResultType.All);
+                            return Break("Send", false, "存在失败数据", Message, @enum.ResultType.All);
                         }
                     }
                     else
                     {
-                        return Break("Send", false, $"数据发送失败,[{IpPort}]不存在", Message, @enum.ResultType.All);
+                        //指定发送
+                        if (ClientIoc.ContainsKey(IpPort))
+                        {
+                            if (ClientIoc[IpPort].SocketObj.Send(Data) <= 0)
+                            {
+                                return Break("Send", false, $"数据发送[{IpPort}]失败", Message, @enum.ResultType.All);
+                            }
+                        }
+                        else
+                        {
+                            return Break("Send", false, $"数据发送失败,[{IpPort}]不存在", Message, @enum.ResultType.All);
+                        }
                     }
+                    return Break("Send", true);
+                }
+                else
+                {
+                    return Break("Send", false, $"未启动");
                 }
-                return Break("Send", true);
             }
             catch (Exception ex)
             {

+ 21 - 9
src/YSAI.DAQ/YSAI.Core/communication/net/udp/UdpOperate.cs

@@ -92,7 +92,7 @@ namespace YSAI.Core.communication.net.udp
                         int alen = Communication.Available;  //判断是不是有数据可以读取
                         if (alen > 0)
                         {
-                            UdpReceiveResult urr = Communication.ReceiveAsync().Result;  //读取数据
+                            UdpReceiveResult urr = Communication.ReceiveAsync(token.Token).Result;  //读取数据
                             if (urr.Buffer.Length > 0)
                             {
                                 OnEventHandler(this, new EventResult(true, $"接收到[{ClassName}]监控数据,来自[{urr.RemoteEndPoint}]", new UdpData.TerminalMessage { IpPort = urr.RemoteEndPoint.ToString(), Data = ByteTool.ByteTrimEnd(urr.Buffer) }, @enum.ResultType.Bytes));  //数据传递出去
@@ -127,13 +127,25 @@ namespace YSAI.Core.communication.net.udp
                 {
                     return Break("On", false, "已打开");
                 }
-                Communication = new UdpClient();
-                //设置参数
-                IPEndPoint IpPort = new IPEndPoint(IPAddress.Parse(basics.Ip), basics.Port);
-                //使用广播模式
-                Communication.EnableBroadcast = basics.EnableBroadcast;
-                //连接
-                Communication.Connect(IpPort);
+                if (basics.EnableBroadcast)
+                {
+                    //设置参数
+                    IPEndPoint IpPort = new IPEndPoint(IPAddress.Parse(basics.Ip), basics.Port);
+                    //广播模式
+                    Communication = new UdpClient(IpPort);
+                    //使用广播模式
+                    Communication.EnableBroadcast = basics.EnableBroadcast;
+                }
+                else
+                {
+                    Communication = new UdpClient();
+                    //设置参数
+                    IPEndPoint IpPort = new IPEndPoint(IPAddress.Parse(basics.Ip), basics.Port);
+                    //连接到主站
+                    Communication.Connect(IpPort);
+                    //使用广播模式
+                    Communication.EnableBroadcast = basics.EnableBroadcast;
+                }
                 //当使用发送等待,则不启用监控
                 if (!basics.SendWait)
                 {
@@ -204,7 +216,7 @@ namespace YSAI.Core.communication.net.udp
             {
                 if (Communication != null )
                 {
-                    if (Communication.Send(Data, Data.Length) > 0)
+                    if (Communication.Send(Data, Data.Length,new IPEndPoint(IPAddress.Parse("255.255.255.255"),basics.Port)) > 0)
                     {
                         return Break("Send", true);
                     }

+ 3 - 8
src/YSAI.DAQ/YSAI.Core/communication/net/ws/client/WsClientData.cs

@@ -14,13 +14,9 @@ namespace YSAI.Core.communication.net.ws.client
         public class Basics : BasicsData
         {
             /// <summary>
-            /// 服务端IP
+            /// 主机地址
             /// </summary>
-            public string? Ip { get; set; } = "127.0.0.1";
-            /// <summary>
-            /// 服务器端口
-            /// </summary>
-            public int Port { get; set; } = 6688;
+            public string? Host { get; set; }
             /// <summary>
             /// 是否需要断开重新连接
             /// </summary>
@@ -56,8 +52,7 @@ namespace YSAI.Core.communication.net.ws.client
                     if (SN.Equals(basics.SN) &&
                         SendWait.Equals(basics.SendWait) &&
                         SendWaitInterval.Equals(basics.SendWaitInterval) &&
-                        Ip.Equals(basics.Ip) &&
-                        Port.Equals(basics.Port) &&
+                        Host.Equals(basics.Host) &&
                         InterruptReconnection.Equals(basics.InterruptReconnection) &&
                         Timeout.Equals(basics.Timeout) &&
                         Timeout.Equals(basics.Timeout))

+ 41 - 20
src/YSAI.DAQ/YSAI.Core/communication/net/ws/client/WsClientOperate.cs

@@ -95,10 +95,10 @@ namespace YSAI.Core.communication.net.ws.client
                 {
                     try
                     {
-                        if (Communication.State.Equals(WebSocketState.Open))
+                        if (Communication != null && Communication.State.Equals(WebSocketState.Open))
                         {
-                            ArraySegment<byte> CacheBuffer = new ArraySegment<byte>();
-                            WebSocketReceiveResult result = Communication.ReceiveAsync(CacheBuffer, token.Token).Result;  //读取数据
+                            ArraySegment<byte> CacheBuffer = new ArraySegment<byte>(new byte[1024 * 1024]);
+                            WebSocketReceiveResult result = Communication.ReceiveAsync(CacheBuffer, token.Token).WaitAsync(token.Token).Result;   //读取数据
                             if (result.Count > 0)
                             {
                                 OnEventHandler(this, new EventResult(true, $"接收到[{ClassName}]监控数据", ByteTool.ByteTrimEnd(CacheBuffer.Array), @enum.ResultType.Bytes));  //数据传递出去
@@ -107,6 +107,7 @@ namespace YSAI.Core.communication.net.ws.client
                             {
                                 OnEventHandler(this, new EventResult(false, $"接收到[{ClassName}]监控数据长度错误(小于等于零)"));  //数据传递出去
                                 OffAsync();
+                                return;
                             }
                         }
                         else
@@ -118,6 +119,7 @@ namespace YSAI.Core.communication.net.ws.client
                     {
                         OnEventHandler(this, new EventResult(false, $"[{ClassName}]监控异常,关闭对象:{ex.Message}"));
                         OffAsync();
+                        return;
                     }
                 }
             }, token.Token);
@@ -137,17 +139,22 @@ namespace YSAI.Core.communication.net.ws.client
                 {
                     try
                     {
-                        if (!Communication.State.Equals(WebSocketState.Open))
+                        if (Communication == null || !Communication.State.Equals(WebSocketState.Open))
                         {
-                            if (On().State)
+                            //实例化对象
+                            Communication = new ClientWebSocket();
+                            //创建链接
+                            Uri uri = new Uri($"ws://{basics.Host}");
+                            //连接
+                            if (!Communication.ConnectAsync(uri, token.Token).Wait(basics.Timeout))
                             {
-                                OnEventHandler(this, new EventResult(true, $"[{ClassName}]断线重连成功"));  //数据传递出去
-                                ReconnectionCount = 1;
+                                OnEventHandler(this, new EventResult(false, $"[{ClassName}]断线重连失败,连接超时,重连{ReconnectionCount}次"));  //数据传递出去
+                                ReconnectionCount++;
                             }
                             else
                             {
-                                OnEventHandler(this, new EventResult(false, $"[{ClassName}]断线重连失败,重连{ReconnectionCount}次"));  //数据传递出去
-                                ReconnectionCount++;
+                                OnEventHandler(this, new EventResult(true, $"[{ClassName}]断线重连成功"));  //数据传递出去
+                                ReconnectionCount = 1;
                             }
                         }
                     }
@@ -173,7 +180,7 @@ namespace YSAI.Core.communication.net.ws.client
                 //实例化对象
                 Communication = new ClientWebSocket();
                 //创建链接
-                Uri uri = new Uri($"ws://{basics.Ip}:{basics.Port}");
+                Uri uri = new Uri($"ws://{basics.Host}");
                 //连接
                 if (!Communication.ConnectAsync(uri, CancellationToken.None).Wait(basics.Timeout))
                 {
@@ -223,7 +230,7 @@ namespace YSAI.Core.communication.net.ws.client
             Depart("Off");
             try
             {
-                if (Communication != null && Communication.State.Equals(WebSocketState.Open))
+                if (Communication != null)
                 {
                     //关闭监控
                     if (MonitorSwitch != null)
@@ -247,16 +254,30 @@ namespace YSAI.Core.communication.net.ws.client
                         //任务对象清空
                         InterruptReconnectionTask = null;
                     }
-                    if (Communication.CloseAsync(WebSocketCloseStatus.Empty, "手动关闭", CancellationToken.None).Wait(basics.Timeout))
+                    switch (Communication.State)
                     {
-                        Communication.Dispose();
-                        Communication = null;
-                        return Break("Off", true);
-                    }
-                    else
-                    {
-                        return Break("Off", false,"关闭超时");
+                        case WebSocketState.Open:
+                        case WebSocketState.CloseSent:
+                        case WebSocketState.CloseReceived:
+                            if (Communication.CloseAsync(WebSocketCloseStatus.Empty, null, CancellationToken.None).Wait(basics.Timeout))
+                            {
+                                Communication.Dispose();
+                                Communication = null;
+                                return Break("Off", true);
+                            }
+                            else
+                            {
+                                return Break("Off", false, "关闭超时");
+                            }
+                        case WebSocketState.None:
+                        case WebSocketState.Connecting:
+                        case WebSocketState.Closed:
+                        case WebSocketState.Aborted:
+                            Communication.Dispose();
+                            Communication = null;
+                            return Break("Off", true);
                     }
+                    
                 }
                 return Break("Off", false, "未连接");
             }
@@ -314,7 +335,7 @@ namespace YSAI.Core.communication.net.ws.client
                         {
                             while (!token.IsCancellationRequested)
                             {
-                                ArraySegment<byte> CacheBuffer = new ArraySegment<byte>();
+                                ArraySegment<byte> CacheBuffer = new ArraySegment<byte>(new byte[1024 * 1024]);
                                 WebSocketReceiveResult result = Communication.ReceiveAsync(CacheBuffer, token.Token).Result;  //读取数据
                                 if (result.Count > 0)
                                 {

+ 4 - 10
src/YSAI.DAQ/YSAI.Core/communication/net/ws/service/WsServiceData.cs

@@ -18,14 +18,9 @@ namespace YSAI.Core.communication.net.ws.service
             /// </summary>
             public string? SN { get; set; } = Guid.NewGuid().ToString();
             /// <summary>
-            /// IP
+            /// 支持监控多个,注意必须带 / 结尾
             /// </summary>
-            public string? Ip { get; set; } = "127.0.0.1";
-            /// <summary>
-            /// 端口
-            /// </summary>
-            public int Port { get; set; } = 6688;
-
+            public List<string> LocalHostArray { get; set; }
             /// <summary>
             /// 重写基类中的Equals方法
             /// </summary>
@@ -44,9 +39,8 @@ namespace YSAI.Core.communication.net.ws.service
                 }
                 else
                 {
-                    if (Ip == Obj.Ip &&
-                         SN == Obj.SN &&
-                    Port == Obj.Port)
+                    if (LocalHostArray.SequenceEqual(Obj.LocalHostArray) &&
+                         SN == Obj.SN)
                     {
                         return true;
                     }

+ 61 - 41
src/YSAI.DAQ/YSAI.Core/communication/net/ws/service/WsServiceOperate.cs

@@ -107,13 +107,13 @@ namespace YSAI.Core.communication.net.ws.service
                 {
                     try
                     {
-                        HttpListenerContext httpListenerContext = Communication.GetContextAsync().Result;
+                        HttpListenerContext httpListenerContext = Communication.GetContextAsync().WaitAsync(token.Token).Result;
                         if (httpListenerContext.Request.IsWebSocketRequest)  // 如果是websocket请求
                         {
-                            string IpPort = httpListenerContext.Request.RemoteEndPoint.Address.ToString();
+                            string IpPort = httpListenerContext.Request.RemoteEndPoint.ToString();
                             try
                             {
-                                WebSocketContext webSocketContext = httpListenerContext.AcceptWebSocketAsync(subProtocol: null).Result;
+                                WebSocketContext webSocketContext = httpListenerContext.AcceptWebSocketAsync(subProtocol: null).WaitAsync(token.Token).Result;
                                 if (!ClientIoc.ContainsKey(IpPort))  //当字典中没有这个连接对象
                                 {
                                     CancellationTokenSource token = new CancellationTokenSource();
@@ -121,7 +121,7 @@ namespace YSAI.Core.communication.net.ws.service
                                     {
                                         WebSocketObj = webSocketContext,
                                         Switch = token,
-                                        TaskObj = MonitorMessageTask(token, webSocketContext)
+                                        TaskObj = MonitorMessageTask(token, webSocketContext.WebSocket,IpPort)
                                     };
                                     //把此对象添加到字典中
                                     ClientIoc.AddOrUpdate(IpPort, client, (k, v) => client);
@@ -144,7 +144,6 @@ namespace YSAI.Core.communication.net.ws.service
                     {
                         OnEventHandler(this, new EventResult(false, $"[{ClassName}]监控客户端连接异常:{ex.Message}"));
                     }
-
                 }
             }, token.Token);
         }
@@ -153,19 +152,20 @@ namespace YSAI.Core.communication.net.ws.service
         /// 监控消息任务
         /// </summary>
         /// <param name="token"></param>
+        /// <param name="webSocket"></param>
+        /// <param name="IpPort"></param>
         /// <returns></returns>
-        private Task MonitorMessageTask(CancellationTokenSource token, WebSocketContext webSocket)
+        private Task MonitorMessageTask(CancellationTokenSource token, WebSocket webSocket,string IpPort)
         {
             //起一个新线程来监控
             return Task.Factory.StartNew(() =>
             {
-                string IpPort = $"{webSocket.RequestUri.Authority}:{webSocket.RequestUri.Port}";
-                ArraySegment<byte> DataByte = new ArraySegment<byte>(); //数据缓冲区
+                ArraySegment<byte> DataByte = new ArraySegment<byte>(new byte[1024*1024]); //数据缓冲区
                 while (!token.IsCancellationRequested)
                 {
                     try
                     {
-                        WebSocketReceiveResult result = webSocket.WebSocket.ReceiveAsync(DataByte, token.Token).Result; // 接收数据,并返回数据的长度;
+                        WebSocketReceiveResult result = webSocket.ReceiveAsync(DataByte, token.Token).Result; // 接收数据,并返回数据的长度;
                         if (result.Count > 0)
                         {
                             OnEventHandler(this, new EventResult(true, $"[{IpPort}]数据接收成功", new WsServiceData.ClientMessage { Step = WsServiceData.Steps.消息接收, IpPort = IpPort, Data = DataByte.Array }, @enum.ResultType.Bytes));
@@ -175,6 +175,8 @@ namespace YSAI.Core.communication.net.ws.service
                             OnEventHandler(this, new EventResult(false, $"[{IpPort}]发来的数据长度错误(小于等于零),已强制关闭连接", new WsServiceData.ClientMessage { Step = WsServiceData.Steps.客户端断开, IpPort = IpPort }, @enum.ResultType.All));
                             //移除此客户端
                             RemoveAsync(IpPort);
+                            //强制退出此线程
+                            return;
                         }
                     }
                     catch (Exception ex)
@@ -182,6 +184,7 @@ namespace YSAI.Core.communication.net.ws.service
                         OnEventHandler(this, new EventResult(false, $"监控[{IpPort}]消息异常:{ex.Message}", new WsServiceData.ClientMessage { Step = WsServiceData.Steps.客户端断开, IpPort = IpPort }, @enum.ResultType.All));
                         //移除此客户端
                         RemoveAsync(IpPort);
+                        return;
                     }
                 }
             }, token.Token);
@@ -197,6 +200,12 @@ namespace YSAI.Core.communication.net.ws.service
                 {
                     return Break("On", false, "已打开");
                 }
+                Communication = new HttpListener();
+                foreach (var localHost in basics.LocalHostArray)
+                {
+                    Communication.Prefixes.Add(localHost);
+                }
+                Communication.Start();
                 //监控开关
                 if (MonitorConnectSwitch == null || MonitorConnectSwitch.IsCancellationRequested)
                 {
@@ -242,7 +251,7 @@ namespace YSAI.Core.communication.net.ws.service
                     {
                         item.Value.Switch.Cancel();
                         item.Value.TaskObj.Wait();
-                        item.Value.WebSocketObj.WebSocket.CloseAsync(WebSocketCloseStatus.Empty,"手动关闭",CancellationToken.None);
+                        item.Value.WebSocketObj.WebSocket.CloseAsync(WebSocketCloseStatus.Empty,null,CancellationToken.None);
                         item.Value.WebSocketObj.WebSocket.Abort();
                         item.Value.WebSocketObj.WebSocket.Dispose();
                     }
@@ -281,10 +290,10 @@ namespace YSAI.Core.communication.net.ws.service
                 {
                     ClientIoc[IpPort].Switch.Cancel();
                     ClientIoc[IpPort].TaskObj.Wait();
-                    ClientIoc[IpPort].WebSocketObj.WebSocket.CloseAsync(WebSocketCloseStatus.Empty, "客户端连接异常", CancellationToken.None);
+                    ClientIoc[IpPort].WebSocketObj.WebSocket.CloseAsync(WebSocketCloseStatus.Empty,null, CancellationToken.None);
                     ClientIoc[IpPort].WebSocketObj.WebSocket.Abort();
                     ClientIoc[IpPort].WebSocketObj.WebSocket.Dispose();
-
+                    ClientIoc.Remove(IpPort, out _);
                     return Break("Remove", true);
                 }
                 return Break("Remove", false, "Ip Port 不存在");
@@ -300,7 +309,7 @@ namespace YSAI.Core.communication.net.ws.service
         /// <returns></returns>
         public Task<OperateResult> RemoveAsync(string? Key)
         {
-            return Task.Run(() => RemoveAsync(Key));
+            return Task.Run(() => Remove(Key));
         }
         /// <summary>
         /// 数据发送
@@ -313,48 +322,59 @@ namespace YSAI.Core.communication.net.ws.service
             Depart("Send");
             try
             {
-                List<string> Message = new List<string>();
-                if (string.IsNullOrEmpty(IpPort))
+                if (Communication != null)
                 {
-                    //群发
-                    foreach (var client in ClientIoc)
+                    List<string> Message = new List<string>();
+                    if (string.IsNullOrEmpty(IpPort))
                     {
-                        string IP = $"{client.Value.WebSocketObj.RequestUri.Authority}:{client.Value.WebSocketObj.RequestUri.Port}";
-                        try
+                        //群发
+                        foreach (var client in ClientIoc)
                         {
-                            client.Value.WebSocketObj.WebSocket.SendAsync(new ArraySegment<byte>(Data), WebSocketMessageType.Text, true, CancellationToken.None);
+                            if (ClientIoc.Count.Equals(0))
+                            {
+                                return Break("Send", false, "客户端未连接");
+                            }
+                            string IP = client.Key;
+                            try
+                            {
+                                client.Value.WebSocketObj.WebSocket.SendAsync(new ArraySegment<byte>(Data), WebSocketMessageType.Text, true, CancellationToken.None);
+                            }
+                            catch (Exception ex)
+                            {
+                                Message.Add($"[{IP}]数据发送异常:{ex.Message}");
+                            }
                         }
-                        catch (Exception ex)
+
+                        if (Message.Count > 0)
                         {
-                            Message.Add($"[{IP}]数据发送异常:{ex.Message}");
+                            return Break("Send", false, "存在失败数据", Message, @enum.ResultType.All);
                         }
                     }
-
-                    if (Message.Count > 0)
-                    {
-                        return Break("Send", false, "存在失败数据", Message, @enum.ResultType.All);
-                    }
-                }
-                else
-                {
-                    //指定发送
-                    if (ClientIoc.ContainsKey(IpPort))
+                    else
                     {
-                        try
+                        //指定发送
+                        if (ClientIoc.ContainsKey(IpPort))
                         {
-                            ClientIoc[IpPort].WebSocketObj.WebSocket.SendAsync(new ArraySegment<byte>(Data), WebSocketMessageType.Text, true, CancellationToken.None);
+                            try
+                            {
+                                ClientIoc[IpPort].WebSocketObj.WebSocket.SendAsync(new ArraySegment<byte>(Data), WebSocketMessageType.Text, true, CancellationToken.None);
+                            }
+                            catch (Exception ex)
+                            {
+                                return Break("Send", false, $"数据发送[{IpPort}]异常:{ex.Message}", Message, @enum.ResultType.All);
+                            }
                         }
-                        catch (Exception ex)
+                        else
                         {
-                            return Break("Send", false, $"数据发送[{IpPort}]异常:{ex.Message}", Message, @enum.ResultType.All);
+                            return Break("Send", false, $"数据发送失败,[{IpPort}]不存在", Message, @enum.ResultType.All);
                         }
                     }
-                    else
-                    {
-                        return Break("Send", false, $"数据发送失败,[{IpPort}]不存在", Message, @enum.ResultType.All);
-                    }
+                    return Break("Send", true);
+                }
+                else
+                {
+                    return Break("Send", false, $"未启动");
                 }
-                return Break("Send", true);
             }
             catch (Exception ex)
             {

+ 188 - 58
src/YSAI.DAQ/YSAI.Test.All/Program.cs

@@ -1,80 +1,210 @@
 using System.Collections.Concurrent;
+using System.Text;
+using YSAI.Core.communication.net.tcp.client;
+using YSAI.Core.communication.net.tcp.service;
+using YSAI.Core.communication.net.udp;
+using YSAI.Core.communication.net.ws.client;
+using YSAI.Core.communication.net.ws.service;
 using YSAI.Core.data;
 using YSAI.Core.handler;
 using YSAI.Core.@interface;
 using YSAI.Core.subscription;
 
-//地址参数
-Address address = new Address()
+UdpOperate udpOperate = UdpOperate.Instance(new UdpData.Basics 
 {
-    SN = Guid.NewGuid().ToString(),
-    AddressArray = new List<AddressDetails>()
-};
-for (int i = 0; i < 1000; i++)
+        EnableBroadcast = true,
+        Ip= "0.0.0.0",
+        Port=8081
+});
+udpOperate.OnEvent += UdpOperate_OnEvent;
+OperateResult operateResult = udpOperate.On();
+Console.WriteLine(operateResult.Message);
+
+while (true)
 {
-    address.AddressArray.Add(new AddressDetails
+    for (int i = 0; i < 100; i++)
     {
-        SN = $"测试{i}号采集",
-        AddressName = $"TEST{i}"
-    });
+        string str = Console.ReadLine();
+        operateResult = udpOperate.Send(Encoding.Default.GetBytes(str));
+        Console.WriteLine(operateResult.Message);
+    }
+
+    Console.ReadLine();
+    operateResult = udpOperate.Off();
+    Console.WriteLine(operateResult.Message);
 }
 
+void UdpOperate_OnEvent(object? sender, EventResult e)
+{
+    Console.WriteLine("事件数据:" + e.Message);
+}
 
 
+//TcpServiceOperate tcpServiceOperate = TcpServiceOperate.Instance(new TcpServiceData.Basics
+//{
+//    Ip = "127.0.0.1",
+//    Port = 8888,
+//    MaxNumber = 1000
+//});
 
-TEST tEST = new TEST();
-SubscribeOperate subscribeOperate = SubscribeOperate.Instance(new SubscribeData.Basics()
-{
-    Address = address,
-    Function = tEST.Read,
-});
-subscribeOperate.OnEvent += SubscribeOperate_OnEvent;
-OperateResult operateResult = subscribeOperate.On();
+//tcpServiceOperate.OnEvent += WsServiceOperate_OnEvent;
+//OperateResult operateResult = tcpServiceOperate.On();
+//Console.WriteLine(operateResult.Message);
 
 
+//TcpClientOperate wsClientOperate = TcpClientOperate.Instance(new TcpClientData.Basics
+//{
+//    Ip = "127.0.0.1",
+//    Port = 8888,
+//    InterruptReconnection = true
+//});
+//wsClientOperate.OnEvent += WsServiceOperate_OnEvent;
+//operateResult = wsClientOperate.On();
+//Console.WriteLine(operateResult.Message);
 
-while (true)
-{
-   string comm= Console.ReadLine();
-    if (comm.Equals("close"))
-    {
-        Console.WriteLine(subscribeOperate.Off().Message);
-    }
-}
-void SubscribeOperate_OnEvent(object? sender, EventResult e)
-{
-    ConcurrentDictionary<string, AddressValue> param = e.RData as ConcurrentDictionary<string, AddressValue>;
-    foreach (var item in param)
-    {
-        Console.WriteLine(item.Value.AddressName);
-        Console.WriteLine(item.Value.Value);
-        Console.WriteLine("---------------------");
-    }
-}
 
-class TEST : IBaseAbstract
-{
-    protected override string LogHead => "[ TEST 操作 ]";
-    protected override string ClassName => "TEST";
-    public OperateResult Read(Address address)
-    {
-        Depart("Read");
-        //节点数据
-        ConcurrentDictionary<string, AddressValue> param = new ConcurrentDictionary<string, AddressValue>();
-        foreach (var item in address.AddressArray)
-        {
-            //数据处理
-            AddressValue addressValue = AddressHandler.ExecuteDispose(item, new Random().NextDouble().ToString());
-
-            //AddressValue addressValue = YSAI.Core.data.AddressHandler.ExecuteDispose(item, "1");
-
-            //数据添加
-            param.AddOrUpdate(item.AddressName, addressValue, (k, v) => addressValue);
-        }
-        return Break("Read", true, RData: param, RType: YSAI.Core.@enum.ResultType.KeyValue);
-    }
+//while (true)
+//{
+//    for (int i = 0; i < 1; i++)
+//    {
+//        string str = Console.ReadLine();
 
+//        operateResult = tcpServiceOperate.Send(Encoding.Default.GetBytes(str));
+//        Console.WriteLine(operateResult.Message);
 
+//        operateResult = wsClientOperate.Send(Encoding.Default.GetBytes(str));
+//        Console.WriteLine(operateResult.Message);
+//    }
 
+//    Console.ReadLine();
+//    operateResult = tcpServiceOperate.Off();
+//    Console.WriteLine(operateResult.Message);
+//    operateResult = wsClientOperate.Off();
+//    Console.WriteLine(operateResult.Message);
+//}
 
-}
+//void WsServiceOperate_OnEvent(object? sender, EventResult e)
+//{
+//    Console.WriteLine("事件数据:" + e.Message);
+//}
+
+//WsServiceOperate wsServiceOperate = WsServiceOperate.Instance(new WsServiceData.Basics
+//{
+//    LocalHostArray = new List<string> { "http://localhost:8888/" }
+//});
+
+//wsServiceOperate.OnEvent += WsServiceOperate_OnEvent;
+//OperateResult operateResult = wsServiceOperate.On();
+//Console.WriteLine(operateResult.Message);
+
+
+//WsClientOperate wsClientOperate = WsClientOperate.Instance(new WsClientData.Basics
+//{
+//    Host = "localhost:8888",
+//    InterruptReconnection = true
+//});
+//wsClientOperate.OnEvent += WsServiceOperate_OnEvent;
+//operateResult = wsClientOperate.On();
+//Console.WriteLine(operateResult.Message);
+
+
+
+//while (true)
+//{
+//    for (int i = 0; i < 1; i++)
+//    {
+//        string str = Console.ReadLine();
+
+//        operateResult = wsServiceOperate.Send(Encoding.Default.GetBytes(str));
+//        Console.WriteLine(operateResult.Message);
+
+//        operateResult = wsClientOperate.Send(Encoding.Default.GetBytes(str));
+//        Console.WriteLine(operateResult.Message);
+//    }
+//    Console.ReadLine();
+//    operateResult = wsServiceOperate.Off();
+//    Console.WriteLine(operateResult.Message);
+//    operateResult = wsClientOperate.Off();
+//    Console.WriteLine(operateResult.Message);
+//}
+
+//void WsServiceOperate_OnEvent(object? sender, EventResult e)
+//{
+//    Console.WriteLine("事件数据:" + e.Message);
+//}
+
+
+////地址参数
+//Address address = new Address()
+//{
+//    SN = Guid.NewGuid().ToString(),
+//    AddressArray = new List<AddressDetails>()
+//};
+//for (int i = 0; i < 1000; i++)
+//{
+//    address.AddressArray.Add(new AddressDetails
+//    {
+//        SN = $"测试{i}号采集",
+//        AddressName = $"TEST{i}"
+//    });
+//}
+
+
+
+
+//TEST tEST = new TEST();
+//SubscribeOperate subscribeOperate = SubscribeOperate.Instance(new SubscribeData.Basics()
+//{
+//    Address = address,
+//    Function = tEST.Read,
+//});
+//subscribeOperate.OnEvent += SubscribeOperate_OnEvent;
+//OperateResult operateResult = subscribeOperate.On();
+
+
+
+//while (true)
+//{
+//   string comm= Console.ReadLine();
+//    if (comm.Equals("close"))
+//    {
+//        Console.WriteLine(subscribeOperate.Off().Message);
+//    }
+//}
+//void SubscribeOperate_OnEvent(object? sender, EventResult e)
+//{
+//    ConcurrentDictionary<string, AddressValue> param = e.RData as ConcurrentDictionary<string, AddressValue>;
+//    foreach (var item in param)
+//    {
+//        Console.WriteLine(item.Value.AddressName);
+//        Console.WriteLine(item.Value.Value);
+//        Console.WriteLine("---------------------");
+//    }
+//}
+
+//class TEST : IBaseAbstract
+//{
+//    protected override string LogHead => "[ TEST 操作 ]";
+//    protected override string ClassName => "TEST";
+//    public OperateResult Read(Address address)
+//    {
+//        Depart("Read");
+//        //节点数据
+//        ConcurrentDictionary<string, AddressValue> param = new ConcurrentDictionary<string, AddressValue>();
+//        foreach (var item in address.AddressArray)
+//        {
+//            //数据处理
+//            AddressValue addressValue = AddressHandler.ExecuteDispose(item, new Random().NextDouble().ToString());
+
+//            //AddressValue addressValue = YSAI.Core.data.AddressHandler.ExecuteDispose(item, "1");
+
+//            //数据添加
+//            param.AddOrUpdate(item.AddressName, addressValue, (k, v) => addressValue);
+//        }
+//        return Break("Read", true, RData: param, RType: YSAI.Core.@enum.ResultType.KeyValue);
+//    }
+
+
+
+
+//}

+ 19 - 0
src/YSAI.DAQ/YSAI.Test.Console/Program.cs

@@ -8,6 +8,8 @@ using System.Collections.Concurrent;
 using System.Collections.Generic;
 using System.Text;
 using System.Text.RegularExpressions;
+using YSAI.Core.communication.net.ws.client;
+using YSAI.Core.communication.net.ws.service;
 using YSAI.Core.communication.serial;
 using YSAI.Core.data;
 using YSAI.Core.@enum;
@@ -29,7 +31,24 @@ using ZstdSharp.Unsafe;
 using static YSAI.Modbus.client.ModbusClientData;
 
 
+//WsServiceOperate wsServiceOperate = WsServiceOperate.Instance(new WsServiceData.Basics 
+//{
+//    Ip = "127.0.0.1",
+//    Port=8886
+//});
+
+//wsServiceOperate.OnEvent += WsServiceOperate_OnEvent;
+//OperateResult operateResult = wsServiceOperate.On();
+//Console.WriteLine(operateResult.Message);
+//while (true)
+//{
+//    Console.ReadLine();
+//}
 
+//void WsServiceOperate_OnEvent(object? sender, EventResult e)
+//{
+//    Console.WriteLine(e.Message);
+//}
 
 //SerialOperate serialOperate = SerialOperate.Instance(new SerialData.Basics 
 //{