CrazyIter_Bin 9 달 전
부모
커밋
27864008a5

+ 11 - 87
TEAMModelOS.Extension/HTEX.ScreenClient/Program.cs

@@ -12,84 +12,7 @@ namespace HTEX.ScreenClient
     {
         public static void Main(string[] args)
         {
-            long  CpuCoreCount = 0;
-            long  MenemorySize = 0;
-            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ) {
- 
-                // 获取CPU核心数
-                int processorCount = Environment.ProcessorCount;
-                 
-                Console.WriteLine("CPU 核心数: " + processorCount);
-                using (ManagementClass managementClass = new ManagementClass("Win32_Processor"))
-                {
-                    using (ManagementObjectCollection managementObjectCollection = managementClass.GetInstances())
-                    {
-                        foreach (ManagementObject managementObject in managementObjectCollection)
-                        {
-                            CpuCoreCount += Convert.ToInt32(managementObject.Properties["NumberOfLogicalProcessors"].Value);
-                        }
-                    }
-                }
-                using (ManagementClass mc = new ManagementClass("Win32_ComputerSystem"))
-                {
-                    using (ManagementObjectCollection moc = mc.GetInstances())
-                    {
-                        foreach (ManagementObject mo in moc)
-                        {
-                            if (mo["TotalPhysicalMemory"]!= null)
-                            {
-                                MenemorySize = Convert.ToInt64(mo["TotalPhysicalMemory"]);
-                            }
-                        }
-                    }
-                }
-            }
-            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) {
-                int processorCount = Environment.ProcessorCount;
-                Console.WriteLine("CPU 核心数: " + processorCount);
-                string[] cpu_lines = File.ReadAllLines("/proc/cpuinfo");
-                CpuCoreCount= cpu_lines.Count(line => line.StartsWith("processor", StringComparison.OrdinalIgnoreCase));
-                string[] mem_lines = File.ReadAllLines("/proc/meminfo");
-                var match = mem_lines.FirstOrDefault(line => line.StartsWith("MemTotal:"));
-                if (match != null)
-                {
-                    var matchResult = Regex.Match(match, @"\d+");
-                    if (matchResult.Success)
-                    {
-                        MenemorySize=  long.Parse(matchResult.Value);
-                    }
-                }
-            } else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) {
-                using (var process = new Process())
-                {
-                    process.StartInfo.FileName = "/usr/sbin/sysctl";
-                    process.StartInfo.Arguments = "-n hw.ncpu";
-                    process.StartInfo.RedirectStandardOutput = true;
-                    process.StartInfo.UseShellExecute = false;
-                    process.Start();
-                    string output = process.StandardOutput.ReadToEnd().Trim();
-                    int coreCount;
-                    if (int.TryParse(output, out coreCount))
-                    {
-                        CpuCoreCount= coreCount;
-                    }
-                }
-                using (var process = new Process())
-                {
-                    process.StartInfo.FileName = "/usr/sbin/sysctl";
-                    process.StartInfo.Arguments = "-n hw.memsize";
-                    process.StartInfo.RedirectStandardOutput = true;
-                    process.StartInfo.UseShellExecute = false;
-                    process.Start();
-                    string output = process.StandardOutput.ReadToEnd().Trim();
-                    long memorySize;
-                    if (long.TryParse(output, out memorySize))
-                    {
-                        MenemorySize=  memorySize;
-                    }
-                }
-            }
-            Console.WriteLine("CPU 核心数: " + CpuCoreCount+",RAM 大小:"+MenemorySize);
+           
             var builder = WebApplication.CreateBuilder(args);
    
             builder.Services.AddControllers();
@@ -101,8 +24,8 @@ namespace HTEX.ScreenClient
                 //options.ListenAnyIP(4001, options => {
                 //   // options.UseHttps("Crt/iteden.pfx", "iteden"); 
                 //});
-                options.ListenAnyIP(1883, options => {/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
-                options.ListenAnyIP(5000, options => {/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
+                options.ListenAnyIP(CheckOrNewPort(1883), options => {/*options.UseHttps("Crt/iteden.pfx", "iteden");*/ });
+                options.ListenAnyIP(CheckOrNewPort(5000), options => {/* options.UseHttps("Configs/Crt/iteden.pfx", "iteden"); */}); // Default HTTP pipeline
             });
 
             builder.Services.AddHostedService<SignalRScreenClientHub>();
@@ -147,19 +70,16 @@ namespace HTEX.ScreenClient
                 {
                     // 尝试连接到指定的IP地址和端口  
                     IAsyncResult result = socket.BeginConnect(ipAddress, port, null, null);
-
                     // 等待连接尝试完成(这里简单地使用Socket的ConnectTimeout,但更常见的做法是使用超时等待或异步回调)  
                     bool success = result.AsyncWaitHandle.WaitOne(TimeSpan.FromSeconds(1), true);
-
                     if (success)
                     {
                         // 如果连接成功,则端口被占用  
                         socket.EndConnect(result);
                         isPortAvailable = false;
-
                         // 可选:如果需要,可以在这里关闭连接  
-                        socket.Shutdown(SocketShutdown.Both);
-                        socket.Close();
+                        //socket.Shutdown(SocketShutdown.Both);
+                        //socket.Close();
                     }
                     else
                     {
@@ -169,17 +89,21 @@ namespace HTEX.ScreenClient
             }
             catch (SocketException ex)
             {
-                Console.WriteLine(ex.Message);
+                Console.WriteLine($"{ex.Message},{ex.SocketErrorCode}");
                 // 如果错误代码为10048,则表示地址已被使用  
                 if (ex.SocketErrorCode == SocketError.AddressAlreadyInUse)
                 {
                     isPortAvailable = false;
                 }
+                if (ex.SocketErrorCode==SocketError.ConnectionRefused) 
+                {
+                    isPortAvailable=true;
+                }
             }
             catch (Exception ex)
             {
-                isPortAvailable = false;
                 Console.WriteLine(ex.Message);
+                isPortAvailable = false;
             }
             return isPortAvailable;
         }

+ 97 - 8
TEAMModelOS.Extension/HTEX.ScreenClient/Services/SignalRScreenClientHub.cs

@@ -5,6 +5,8 @@ using Microsoft.AspNetCore.Hosting.Server;
 using Microsoft.AspNetCore.Hosting.Server.Features;
 using Microsoft.AspNetCore.SignalR.Client;
 using Microsoft.Extensions.Configuration;
+using System.Diagnostics;
+using System.Management;
 using System.Net;
 using System.Net.Http.Headers;
 using System.Net.NetworkInformation;
@@ -12,6 +14,7 @@ using System.Runtime.InteropServices;
 using System.Text;
 using System.Text.Json;
 using System.Text.Json.Nodes;
+using System.Text.RegularExpressions;
 using System.Threading.Tasks;
 using System.Web;
 using TEAMModelOS.SDK;
@@ -52,9 +55,9 @@ namespace HTEX.ScreenClient.Services
             device.timeout = Timeout;
             device.delay = Delay;
             device.screenUrl = ScreenUrl;
-            await StartHubConnectionAsync(stoppingToken, clientid, CenterUrl);
+            await StartHubConnectionAsync( clientid, CenterUrl);
         }
-        private async Task StartHubConnectionAsync(CancellationToken cancellationToken,string clientid, string? CenterUrl)
+        private async Task StartHubConnectionAsync(string clientid, string? CenterUrl)
         {
             //重写重连策略,防止服务端更新,断线后,客户端达到最大连接次数,依然连线不上服务端。
             var reconnectPolicy = new ExponentialBackoffReconnectPolicy(TimeSpan.FromSeconds(10), _logger); // 尝试重连的最大次数,这里使用 int.MaxValue 表示无限次
@@ -99,7 +102,7 @@ namespace HTEX.ScreenClient.Services
                         _logger.LogInformation($"任务领取失败,{message.ToJsonString()}");
                     }
                 });
-                await hubConnection.StartAsync(cancellationToken);
+                await hubConnection.StartAsync();
             }
             catch (Exception ex)
             {
@@ -111,8 +114,8 @@ namespace HTEX.ScreenClient.Services
                 {
                     try
                     {
-                        await Task.Delay(retryDelaySeconds * 1000, cancellationToken); // 等待一段时间后重试  
-                        await hubConnection.StartAsync(cancellationToken);
+                        await Task.Delay(retryDelaySeconds * 1000); // 等待一段时间后重试  
+                        await hubConnection.StartAsync();
                         _logger.LogInformation("SignalR连接成功(重试后)!");
                         break; // 连接成功,退出循环  
                     }
@@ -237,12 +240,97 @@ namespace HTEX.ScreenClient.Services
             }
             _logger.LogInformation($"计算机名:{hostName}");
             _logger.LogInformation($"系统名称:{RuntimeInformation.OSDescription}");
-           
+            int CpuCoreCount = 0;
+            long MenemorySize = 0;
+            if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows))
+            {
+                // 获取CPU核心数
+                //int processorCount = Environment.ProcessorCount;
+               //Console.WriteLine("CPU 核心数: " + processorCount);
+                using (ManagementClass managementClass = new ManagementClass("Win32_Processor"))
+                {
+                    using (ManagementObjectCollection managementObjectCollection = managementClass.GetInstances())
+                    {
+                        foreach (ManagementObject managementObject in managementObjectCollection)
+                        {
+                            CpuCoreCount += Convert.ToInt32(managementObject.Properties["NumberOfLogicalProcessors"].Value);
+                        }
+                    }
+                }
+                using (ManagementClass mc = new ManagementClass("Win32_ComputerSystem"))
+                {
+                    using (ManagementObjectCollection moc = mc.GetInstances())
+                    {
+                        foreach (ManagementObject mo in moc)
+                        {
+                            if (mo["TotalPhysicalMemory"]!= null)
+                            {
+                                MenemorySize = Convert.ToInt64(mo["TotalPhysicalMemory"]);
+                            }
+                        }
+                    }
+                }
+            }
+            else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux))
+            {
+                //int processorCount = Environment.ProcessorCount;
+               // Console.WriteLine("CPU 核心数: " + processorCount);
+                string[] cpu_lines = File.ReadAllLines("/proc/cpuinfo");
+                CpuCoreCount= cpu_lines.Count(line => line.StartsWith("processor", StringComparison.OrdinalIgnoreCase));
+                string[] mem_lines = File.ReadAllLines("/proc/meminfo");
+                var match = mem_lines.FirstOrDefault(line => line.StartsWith("MemTotal:"));
+                if (match != null)
+                {
+                    var matchResult = Regex.Match(match, @"\d+");
+                    if (matchResult.Success)
+                    {
+                        MenemorySize=  long.Parse(matchResult.Value);
+                    }
+                }
+            }
+            else if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX))
+            {
+                using (var process = new Process())
+                {
+                    process.StartInfo.FileName = "/usr/sbin/sysctl";
+                    process.StartInfo.Arguments = "-n hw.ncpu";
+                    process.StartInfo.RedirectStandardOutput = true;
+                    process.StartInfo.UseShellExecute = false;
+                    process.Start();
+                    string output = process.StandardOutput.ReadToEnd().Trim();
+                    int coreCount;
+                    if (int.TryParse(output, out coreCount))
+                    {
+                        CpuCoreCount= coreCount;
+                    }
+                }
+                using (var process = new Process())
+                {
+                    process.StartInfo.FileName = "/usr/sbin/sysctl";
+                    process.StartInfo.Arguments = "-n hw.memsize";
+                    process.StartInfo.RedirectStandardOutput = true;
+                    process.StartInfo.UseShellExecute = false;
+                    process.Start();
+                    string output = process.StandardOutput.ReadToEnd().Trim();
+                    long memorySize;
+                    if (long.TryParse(output, out memorySize))
+                    {
+                        MenemorySize=  memorySize;
+                    }
+                }
+            }
+
+            //Console.WriteLine("CPU 核心数: " + CpuCoreCount+",RAM 大小:"+MenemorySize);
+            _logger.LogInformation($"内存大小:{MenemorySize}");
+            _logger.LogInformation($"核心数量:{CpuCoreCount}");
+            device.cpu=CpuCoreCount;
+            device.ram=MenemorySize;
             var nics = NetworkInterface.GetAllNetworkInterfaces();
             foreach (var nic in nics)
             {
                 if (nic.OperationalStatus == OperationalStatus.Up)
                 {
+                    var name = $"{nic.Name}-{nic.Description}";
                     var mac = nic.GetPhysicalAddress().ToString();
                     var properties = nic.GetIPProperties();
                     var unicastAddresses = properties.UnicastAddresses;
@@ -251,10 +339,11 @@ namespace HTEX.ScreenClient.Services
                         if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
                         {
                             var ip = unicast.Address.ToString();
-                            Network network= new Network() { mac=mac, ip=ip };
-                            if (!string.IsNullOrWhiteSpace(mac.ToString()))
+                            Network network= new Network() { mac=mac, ip=ip ,name= name};
+                            if (!string.IsNullOrWhiteSpace(mac.ToString())  && !mac.Equals("000000000000"))
                             {
                                 device.networks.Add(network);
+                                _logger.LogInformation($"网卡名称: {name}");
                                 _logger.LogInformation($"网卡地址: {mac}");
                                 _logger.LogInformation($"内网地址: {ip}");
                             }

+ 9 - 0
TEAMModelOS.SDK/Models/Service/GenPDFService.cs

@@ -880,6 +880,14 @@ namespace TEAMModelOS.SDK
         /// </summary>
         public string? os { get; set; }
         /// <summary>
+        /// CPU核心数量
+        /// </summary>
+        public int cpu { get; set; } 
+        /// <summary>
+        /// 内存大小
+        /// </summary>
+        public long ram { get; set;}
+        /// <summary>
         /// 远程ip
         /// </summary>
         public string? remote { get; set; }
@@ -910,6 +918,7 @@ namespace TEAMModelOS.SDK
     }
     public class Network
     {
+        public string? name { get; set; }
         public string? mac { get; set; }
         public string? ip { get; set; }
     }