SignalRClientHub.cs 6.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. 
  2. using Microsoft.AspNetCore.Hosting.Server;
  3. using Microsoft.AspNetCore.Hosting.Server.Features;
  4. using Microsoft.AspNetCore.SignalR.Client;
  5. using Microsoft.Extensions.Configuration;
  6. using System.Net;
  7. using System.Net.NetworkInformation;
  8. using System.Runtime.InteropServices;
  9. using System.Text;
  10. using System.Text.Json;
  11. using System.Text.Json.Nodes;
  12. using System.Web;
  13. using TEAMModelOS.SDK;
  14. using TEAMModelOS.SDK.Extension;
  15. namespace HTEX.ScreenClient.Services
  16. {
  17. public class SignalRClientHub : BackgroundService, IDisposable
  18. {
  19. private readonly IConfiguration _configuration;
  20. private readonly ILogger<SignalRClientHub> _logger;
  21. private readonly IHttpClientFactory _httpClientFactory;
  22. private readonly IServiceProvider _services;
  23. private IEnumerable<string>? _url = new List<string>();
  24. public SignalRClientHub(IConfiguration configuration,ILogger<SignalRClientHub> logger,IHttpClientFactory httpClientFactory, IServiceProvider services,IHostApplicationLifetime lifetime)
  25. {
  26. _configuration=configuration;
  27. _logger=logger;
  28. _httpClientFactory=httpClientFactory;
  29. _services=services;
  30. lifetime.ApplicationStarted.Register(() => {
  31. var server = _services.GetService<IServer>();
  32. _url = server?.Features.Get<IServerAddressesFeature>()?.Addresses;
  33. });
  34. }
  35. private List<string> messages = new List<string>();
  36. protected async override Task ExecuteAsync(CancellationToken stoppingToken)
  37. {
  38. var device = await GetClientInfo();
  39. string hashData = $"{device.name}-{device.remote}-{device.port}-{device.os}-{string.Join(",",device.networks.Select(x=>$"{x.mac}-{x.ip}"))}";
  40. string clientid = ShaHashHelper.GetSHA256(hashData);
  41. string? CenterUrl = _configuration.GetSection("ScreenClient:CenterUrl").Value;
  42. string? ScreenUrl = _configuration.GetSection("ScreenClient:ScreenUrl").Value;
  43. long Timeout = _configuration.GetValue<long>("ScreenClient:Timeout");
  44. long Delay = _configuration.GetValue<long>("ScreenClient:Delay");
  45. device.timeout = Timeout;
  46. device.delay = Delay;
  47. device.screenUrl = ScreenUrl;
  48. HubConnection hubConnection = new HubConnectionBuilder()
  49. .WithUrl($"{CenterUrl}/signalr/screen?grant_type=bookjs_api&clientid={clientid}&device={HttpUtility.UrlEncode(device.ToJsonString(),Encoding.Unicode)}") //only one slash
  50. .WithAutomaticReconnect()
  51. .ConfigureLogging(logging =>
  52. {
  53. logging.SetMinimumLevel(LogLevel.Information);
  54. logging.AddConsole();
  55. })
  56. .Build();
  57. hubConnection.On<JsonElement>("ReceiveConnection", ( message) =>
  58. {
  59. var encodedMsg = $" {message}";
  60. _logger.LogInformation($"连接成功:{message.ToJsonString()}");
  61. messages.Add(encodedMsg);
  62. });
  63. hubConnection.On<JsonElement>("ReceiveMessage", (message) =>
  64. {
  65. var encodedMsg = $"{message}";
  66. messages.Add(encodedMsg);
  67. });
  68. await hubConnection.StartAsync();
  69. }
  70. public async Task<ClientDevice> GetClientInfo()
  71. {
  72. string hostName =$"{Environment.UserName}-{Dns.GetHostName()}" ;
  73. string os = RuntimeInformation.OSDescription;
  74. //获取当前客户端的服务端口
  75. var _httpClient = _httpClientFactory.CreateClient();
  76. ClientDevice device = new ClientDevice { name =hostName, os= os };
  77. HttpResponseMessage message = await _httpClient.PostAsJsonAsync("https://www.teammodel.cn/core/system-info", new { });
  78. if (message.IsSuccessStatusCode)
  79. {
  80. JsonNode? json = JsonSerializer.Deserialize<JsonNode>(await message.Content.ReadAsStringAsync());
  81. var ip = json?["ip"];
  82. var region = json?["region"];
  83. _logger.LogInformation($"远程地址:{ip}");
  84. _logger.LogInformation($"所属地区:{region}");
  85. device.remote=ip?.ToString();
  86. device.region=region?.ToString();
  87. }
  88. _logger.LogInformation($"计算机名:{hostName}");
  89. _logger.LogInformation($"系统名称:{RuntimeInformation.OSDescription}");
  90. var nics = NetworkInterface.GetAllNetworkInterfaces();
  91. foreach (var nic in nics)
  92. {
  93. if (nic.OperationalStatus == OperationalStatus.Up)
  94. {
  95. var mac = nic.GetPhysicalAddress().ToString();
  96. var properties = nic.GetIPProperties();
  97. var unicastAddresses = properties.UnicastAddresses;
  98. foreach (var unicast in unicastAddresses)
  99. {
  100. if (unicast.Address.AddressFamily == System.Net.Sockets.AddressFamily.InterNetwork)
  101. {
  102. var ip = unicast.Address.ToString();
  103. Network network= new Network() { mac=mac, ip=ip };
  104. if (!string.IsNullOrWhiteSpace(mac.ToString()))
  105. {
  106. device.networks.Add(network);
  107. _logger.LogInformation($"网卡地址: {mac}");
  108. _logger.LogInformation($"内网地址: {ip}");
  109. }
  110. }
  111. }
  112. }
  113. }
  114. if (_url!=null)
  115. {
  116. List<int> ports = new List<int>();
  117. foreach (var url in _url)
  118. {
  119. Uri uri = new Uri(url);
  120. ports.Add(uri.Port);
  121. }
  122. device.port= string.Join(",", ports);
  123. _logger.LogInformation($"占用端口: {device.port}");
  124. }
  125. return device ;
  126. }
  127. }
  128. }