From 99da99b13c68c5f2b82da2764d54b92b1b598657 Mon Sep 17 00:00:00 2001 From: czw <selecti@yeah.net> Date: 星期四, 03 七月 2025 11:32:16 +0800 Subject: [PATCH] 1 --- 2025年6月12日/AuxAllWCS/Build/Project/代码/VS自定义类/AutoThread.cs | 267 +++++++++++++++++++++++++++++++++++++++++++++++++++-- 1 files changed, 257 insertions(+), 10 deletions(-) diff --git "a/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" "b/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" index 9708c0d..4abdad7 100644 --- "a/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" +++ "b/2025\345\271\2646\346\234\21012\346\227\245/AuxAllWCS/Build/Project/\344\273\243\347\240\201/VS\350\207\252\345\256\232\344\271\211\347\261\273/AutoThread.cs" @@ -22,6 +22,9 @@ using ServiceStack.Configuration; using ServiceStack; using Spectre.Console; +using System.Net.WebSockets; +using System.Net; +using System.Threading; namespace GZ.Projects.AuxAllWCS { @@ -73,6 +76,8 @@ } // 鎵ц濮旀墭 + if (methodName != "TaskEverythingRun") + return null; return methodDelegate.DynamicInvoke(args); } @@ -122,7 +127,7 @@ public string WriteLine(string value = "") { - + // 鍦ㄨ繖閲屾嫤鎴鐞嗚緭鍑�@@ -251,7 +256,7 @@ { if (tag.wxr1.R44 && !tag.wxr1.R44_LAST && tag.wxr1.R10) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -284,7 +289,7 @@ RedisHelper.Add($"缁村笇灏旀姄鑷�.R10_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { //涓婃姤鏍¢獙銆� ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); @@ -324,7 +329,7 @@ { if (tag.wxr1.R46 && !tag.wxr1.R46_LAST && tag.wxr1.R11) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -356,7 +361,7 @@ RedisHelper.Add($"缁村笇灏旀姄鑷�.R11_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { //涓婃姤鏍¢獙銆� ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); @@ -396,7 +401,7 @@ { if (tag.wxr2.R44 && !tag.wxr2.R44_LAST && tag.wxr2.R10) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -428,7 +433,7 @@ RedisHelper.Add($"缁村笇灏旀姄鑷�.R10_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[0], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { //涓婃姤鏍¢獙銆� ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); @@ -469,7 +474,7 @@ { if (tag.wxr2.R46 && !tag.wxr2.R46_LAST && tag.wxr2.R11) { - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", JsonConvert.SerializeObject(new { @@ -493,16 +498,19 @@ } else { + //LogHelper.Info($"Threadwxr2R 鎵樼洏鏀剧疆淇″彿1銆傘� -{tag.wxr2.R11_LAST}"); if (tag.wxr2.R11_LAST) //鎵樼洏鏀剧疆淇″彿銆傘� { + //LogHelper.Info($"Threadwxr2R 鎵樼洏鏀剧疆淇″彿1銆傘� -{tag.wxr2.R11}"); if (tag.wxr2.R11) { //tag.wxr2.R11_LAST = false; RedisHelper.Add($"缁村笇灏旀姄鑷�.R11_LAST", "false", out string msg); } else - if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode)) + if (TcpServer.TrayIps.TryGetValue(VERX.deviceNo[1], out string traycode) && !string.IsNullOrEmpty(traycode.Trim())) { + LogHelper.Info($"Threadwxr2R 涓婃姤鏍¢獙>{traycode}"); //涓婃姤鏍¢獙銆� ///var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/202", JsonConvert.SerializeObject(new @@ -522,9 +530,17 @@ //鎶ヨ銆� } } - else { TcpServer.TcpServerSend(VERX.deviceNo[1], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); } + else + { + LogHelper.Info($"Threadwxr2R銆傘� -鍙戦�鎵爜"); + TcpServer.TcpServerSend(VERX.deviceNo[1], GZ.Device.PLC.PlcHelper.Hex2Bin("544F4E")); + } } } + } + else + { + Console.WriteLine($"Threadwxr2R 缁村笇灏� 鍙� 璁惧鏈壘鍒般� =================> "); } } @@ -1984,7 +2000,22 @@ return new HkReturnResult { reqCode = model.reqCode, code = 0 }; } + public void TaskEverythingRun() + { + var host = System.Net.Dns.GetHostEntry(System.Net.Dns.GetHostName()); + foreach (var ip in host.AddressList) + { + if (ip.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork) + { + Console.WriteLine($"ip= {ip.ToString()}"); + new TcpServer(ip.ToString()); + var server = new EnhancedWebSocketServer($"http://{ip.ToString()}:8809/").StartAsync(); + //var client = new WebSocketClient($"http://{ip.ToString()}:8809/").ConnectAsync(); + break; + } + } + } @@ -2003,6 +2034,222 @@ } + class EnhancedWebSocketServer + { + private HttpListener _listener; + private readonly string _listenerPrefix; + private readonly ConcurrentDictionary<Guid, WebSocket> _connections = new ConcurrentDictionary<Guid, WebSocket>(); + private CancellationTokenSource _cts = new CancellationTokenSource(); + + public EnhancedWebSocketServer(string url) + { + _listenerPrefix = url; + } + + public async Task StartAsync() + { + try + { + _listener = new HttpListener(); + _listener.Prefixes.Add(_listenerPrefix); + _listener.Start(); + Console.WriteLine($"WebSocket鏈嶅姟鍣ㄥ凡鍚姩锛岀洃鍚�{_listenerPrefix}"); + while (!_cts.IsCancellationRequested) + { + HttpListenerContext context = await _listener.GetContextAsync(); + if (context.Request.IsWebSocketRequest) + { + var wsContext = await context.AcceptWebSocketAsync(null); + var connectionId = Guid.NewGuid(); + _connections[connectionId] = wsContext.WebSocket; + _ = HandleConnectionAsync(connectionId, wsContext.WebSocket, _cts.Token); + } + else + { + context.Response.StatusCode = 400; + context.Response.Close(); + } + } + } + catch (Exception ex) when (ex is HttpListenerException || ex is ObjectDisposedException) + { + // 鏈嶅姟鍣ㄥ仠姝㈡椂鐨勬甯稿紓甯�+ Console.WriteLine("鏈嶅姟鍣ㄦ鍦ㄥ仠姝�.."); + } + } + + private async Task HandleConnectionAsync(Guid connectionId, WebSocket webSocket, CancellationToken ct) + { + var buffer = new byte[1024 * 4]; + try + { + while (webSocket.State == WebSocketState.Open && !ct.IsCancellationRequested) + { + var result = await webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), ct); + + if (result.MessageType == WebSocketMessageType.Close) + { + await webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "瀹㈡埛绔叧闂繛鎺�, ct); + break; + } + + string message = System.Text.Encoding.UTF8.GetString(buffer, 0, result.Count); + Console.WriteLine($"杩炴帴 {connectionId} 鏀跺埌娑堟伅: {message}"); + + // 骞挎挱娑堟伅缁欐墍鏈夊鎴风 + await BroadcastMessageAsync($"瀹㈡埛绔�{connectionId} 璇� {message}"); + } + } + catch (WebSocketException ex) + { + Console.WriteLine($"杩炴帴 {connectionId} 閿欒: {ex.WebSocketErrorCode} - {ex.Message}"); + } + catch (Exception ex) + { + Console.WriteLine($"澶勭悊杩炴帴 {connectionId} 鏃跺嚭閿� {ex.Message}"); + } + finally + { + _connections.TryRemove(connectionId, out _); + webSocket?.Dispose(); + Console.WriteLine($"{DateTime.Now.ToString("HH:mm:ss.fff")} 杩炴帴 {connectionId} 宸插叧闂�); + } + } + + public async Task BroadcastMessageAsync(string message) + { + var buffer = System.Text.Encoding.UTF8.GetBytes(message); + foreach (var connection in _connections) + { + if (connection.Value.State == WebSocketState.Open) + { + try + { + await connection.Value.SendAsync( + new ArraySegment<byte>(buffer), + WebSocketMessageType.Text, + true, + CancellationToken.None); + } + catch (Exception ex) + { + Console.WriteLine($"骞挎挱娑堟伅鍒拌繛鎺�{connection.Key} 澶辫触: {ex.Message}"); + } + } + } + } + + public async Task StopAsync() + { + _cts.Cancel(); + + // 鍏抽棴鎵�湁杩炴帴 + foreach (var connection in _connections) + { + try + { + if (connection.Value.State == WebSocketState.Open) + { + await connection.Value.CloseAsync( + WebSocketCloseStatus.NormalClosure, + "鏈嶅姟鍣ㄥ叧闂�, + CancellationToken.None); + } + connection.Value.Dispose(); + } + catch (Exception ex) + { + Console.WriteLine($"鍏抽棴杩炴帴 {connection.Key} 鏃跺嚭閿� {ex.Message}"); + } + } + + _listener?.Stop(); + _listener?.Close(); + Console.WriteLine("WebSocket鏈嶅姟鍣ㄥ凡鍋滄"); + } + + } + + + + internal class WebSocketClient + { + private ClientWebSocket _webSocket = new ClientWebSocket(); + private readonly Uri _serverUri; + + public WebSocketClient(string serverUrl) + { + _serverUri = new Uri(serverUrl); + } + + public async Task ConnectAsync() + { + try + { + await _webSocket.ConnectAsync(_serverUri, CancellationToken.None); + Console.WriteLine("宸茶繛鎺ュ埌WebSocket鏈嶅姟鍣�); + + // 鍚姩鎺ユ敹娑堟伅浠诲姟 + _ = ReceiveMessagesAsync(); + + // 鍙戦�娴嬭瘯娑堟伅 + await SendMessageAsync("Hello, Server!"); + } + catch (Exception ex) + { + Console.WriteLine($"杩炴帴澶辫触: {ex.Message}"); + } + } + + private async Task ReceiveMessagesAsync() + { + var buffer = new byte[1024]; + try + { + while (_webSocket.State == WebSocketState.Open) + { + var result = await _webSocket.ReceiveAsync(new ArraySegment<byte>(buffer), CancellationToken.None); + if (result.MessageType == WebSocketMessageType.Close) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, string.Empty, CancellationToken.None); + Console.WriteLine("鏈嶅姟鍣ㄥ叧闂簡杩炴帴"); + break; + } + + string message = Encoding.UTF8.GetString(buffer, 0, result.Count); + Console.WriteLine($"鏀跺埌鏈嶅姟鍣ㄦ秷鎭� {message}"); + } + } + catch (Exception ex) + { + Console.WriteLine($"鎺ユ敹娑堟伅鏃跺嚭閿� {ex.Message}"); + } + } + + public async Task SendMessageAsync(string message) + { + if (_webSocket.State != WebSocketState.Open) + { + Console.WriteLine("WebSocket鏈繛鎺ワ紝鏃犳硶鍙戦�娑堟伅"); + return; + } + + byte[] buffer = Encoding.UTF8.GetBytes(message); + await _webSocket.SendAsync(new ArraySegment<byte>(buffer), WebSocketMessageType.Text, true, CancellationToken.None); + } + + public async Task DisconnectAsync() + { + if (_webSocket.State == WebSocketState.Open) + { + await _webSocket.CloseAsync(WebSocketCloseStatus.NormalClosure, "瀹㈡埛绔叧闂繛鎺�, CancellationToken.None); + } + _webSocket.Dispose(); + Console.WriteLine("宸叉柇寮�ebSocket杩炴帴"); + } + } + + class Messss { public bool success { get; set; } -- Gitblit v1.9.1