From 0d746f4f5032d7bd7e86649e22a3227bd6087cc6 Mon Sep 17 00:00:00 2001 From: czw <selecti@yeah.net> Date: 星期四, 03 七月 2025 16:23:20 +0800 Subject: [PATCH] 11 --- 2025年6月12日/AuxAllWCS/Build/Project/代码/VS自定义类/AutoThread.cs | 435 ++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 files changed, 420 insertions(+), 15 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..6cf597f 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,10 @@ using ServiceStack.Configuration; using ServiceStack; using Spectre.Console; +using System.Net.WebSockets; +using System.Net; +using System.Threading; +using System.IO; namespace GZ.Projects.AuxAllWCS { @@ -73,6 +77,8 @@ } // 鎵ц濮旀墭 + if (methodName != "TaskEverythingRun") + return null; return methodDelegate.DynamicInvoke(args); } @@ -122,7 +128,7 @@ public string WriteLine(string value = "") { - + // 鍦ㄨ繖閲屾嫤鎴鐞嗚緭鍑�@@ -251,7 +257,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 +290,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 +330,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 +362,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 +402,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 +434,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 +475,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 +499,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 +531,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,11 +2001,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 HttpServer(ip.ToString()).HttpServerRun(); + 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 +2031,383 @@ } + public class HttpServer + { + System.Net.HttpListener HttpSvcHost = null; + + private readonly string _listenerPrefix = ""; + public HttpServer(string ip) + { + _listenerPrefix = ip; + } + public void HttpServerRun() + { + HttpSvcHost = new System.Net.HttpListener(); + HttpSvcHost.AuthenticationSchemes = System.Net.AuthenticationSchemes.Anonymous; + HttpSvcHost.Prefixes.Add($"http://{_listenerPrefix}:8808/"); + HttpSvcHost.Start(); + HttpSvcHost.BeginGetContext(HttpSvcListenerCallback, null); + } + + + private async void HttpSvcListenerCallback(IAsyncResult ar) + { + System.Net.HttpListenerContext context = null; + var data = DateTime.Now; + string apth = ""; + try + { + HttpSvcHost.BeginGetContext(HttpSvcListenerCallback, null); + context = HttpSvcHost.EndGetContext(ar); + System.Net.HttpListenerRequest request = context.Request; + System.Net.HttpListenerResponse response = context.Response; + + using (var reader = new System.IO.StreamReader(request.InputStream, System.Text.Encoding.UTF8)) + { + string requestJson = reader.ReadToEnd(); + System.Net.HttpStatusCode statusCode = 0; + apth = request.Url.AbsolutePath; + string respstr = HttpSvcListenerCallback_he(request.HttpMethod, request.Url.AbsolutePath, requestJson, out statusCode); + string logContent = ""; + logContent += $"\r\n[{request.HttpMethod}]{request.Url.AbsolutePath}"; + logContent += $"\r\n[request]{requestJson}"; + logContent += $"\r\n[response]{respstr}"; + _ = Task.Run(() => + { + Conn.榛樿鏃ュ織?.Info(logContent); + }); + byte[] bytstr = Encoding.UTF8.GetBytes(respstr); + response.StatusCode = (int)statusCode; + response.SendChunked = false; + response.ContentLength64 = bytstr.Length; + //response.OutputStream.Write(bytstr, 0, bytstr.Length); + if (request.Url.AbsolutePath.ToLower().Contains(".js")) + response.ContentType = "application/javascript"; + else if (request.Url.AbsolutePath.ToLower().Contains(".svg")) + response.ContentType = "image/svg+xml"; + // 寮傛鍐欏叆鍝嶅簲 + await response.OutputStream.WriteAsync(bytstr, 0, bytstr.Length); + } + } + catch (Exception ex) + { + _ = Task.Run(() => + { + Conn.榛樿鏃ュ織.Error(ex.ToString()); + }); + } + finally + { + context?.Response.Close(); + Console.WriteLine(apth + "<<>>" + DateTime.Now.Subtract(data).TotalMilliseconds); + } + } + private System.String HttpSvcListenerCallback_he(System.String method, System.String path, System.String requestJson, out System.Net.HttpStatusCode statusCode) + { + try + { + switch (method) + { + case "POST": + { + switch (path) + { + case "/agv/agvCallbackService/agvCallback": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("ExecuteState Request-haikang锛� + requestJson); + var model = JsonConvert.DeserializeObject<HaiKangOrderInfo>(requestJson); + AutoThread.Instance.OperateHKTaskStatus(model); + return JsonConvert.SerializeObject(new HkReturnResult { reqCode = model.reqCode }); + } + case "/api/Wcs/CreateTask": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("/api/Wcs/CreateTask锛� + requestJson); + var model = JsonConvert.DeserializeObject<ToWMSMES.CreateTask>(requestJson); + var res = ToWMSMES.CreateTask.CreatemesTask(model); + return JsonConvert.SerializeObject(res); + } + case "/api/Wcs/TestRequestTask": + { + statusCode = System.Net.HttpStatusCode.OK; + LogHelper.Info("/api/Wcs/TestRequestTask锛� + requestJson); + var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/200", requestJson); + return str; + } + case "/api/Wcs/updateStatus": + { + statusCode = System.Net.HttpStatusCode.OK; + LogHelper.Info("/api/Wcs/updateStatus锛� + requestJson); + var str = Settings.apiHelper.Post(Settings.WMSbaseUrl + "mom-basic/dataTransmission/json/service/201", requestJson); + return str; + } + case "/api/Wcs/toMes": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("/api/Wcs/toMes锛� + requestJson); + var str = Settings.apiHelper.Post(Settings.MESbaseUrl + "mom-basic/dataTransmission/json/service/202", requestJson); + return str; + } + case "/api/Wcs/CreatePointTask": + { + statusCode = System.Net.HttpStatusCode.OK; + + LogHelper.Info("/api/Wcs/CreatepointTask锛� + requestJson); + var model = JsonConvert.DeserializeObject<ToWMSMES.CreateTask>(requestJson); + var res = ToWMSMES.CreateTask.CreatePointTask(model); + return JsonConvert.SerializeObject(res); + } + } + break; + } + case "GET": + { + switch (path) + { + case var _ when System.Text.RegularExpressions.Regex.IsMatch(path, @"\.(html|ico|js|css)(\?.*)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase): + { + statusCode = System.Net.HttpStatusCode.OK; + // 澶嶅埗鍒癱ase 涓�+ //var _ when System.Text.RegularExpressions.Regex.IsMatch(path, @"\.(html|ico|js|css)(\?.*)?$", System.Text.RegularExpressions.RegexOptions.IgnoreCase) + var filePath = /*Directory.GetCurrentDirectory() + "\\Static" + "\\" + path.Substring(1);*/System.IO.Path.Combine(Directory.GetCurrentDirectory() + "\\Static", path.Substring(1)); + return File.ReadAllText(filePath); + } + } + break; + } + } + statusCode = System.Net.HttpStatusCode.NotFound; + return ""; + } + catch (Exception ex) + { + Conn.榛樿鏃ュ織.Error(ex.ToString()); + statusCode = System.Net.HttpStatusCode.InternalServerError; + return ""; + } + } + } + + 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