UdpListenerService.cs 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104
  1. using AntDesign;
  2. using EasyTemplate.Tool;
  3. using EasyTemplate.Tool.Entity;
  4. using Masuit.Tools;
  5. using Microsoft.AspNetCore.Components;
  6. using Microsoft.Extensions.Hosting;
  7. using Microsoft.Extensions.Logging;
  8. using OneOf.Types;
  9. using SqlSugar;
  10. using System.Globalization;
  11. using System.Net.Sockets;
  12. using System.Reflection.Emit;
  13. using System.Runtime.InteropServices;
  14. using System.Security.Cryptography;
  15. using System.Text;
  16. using System.Xml.Linq;
  17. using EasyTemplate.Service;
  18. using static System.Runtime.InteropServices.JavaScript.JSType;
  19. using Microsoft.Extensions.DependencyInjection;
  20. namespace EasyTemplate.Service
  21. {
  22. public class UdpListenerService : IHostedService
  23. {
  24. private readonly ILogger<UdpListenerService> _logger;
  25. private UdpClient? _udpClient;
  26. public static List<string> ReceivedMessages { get; } = new();
  27. public Dictionary<int, NozzleState> g_mNozzleState = new Dictionary<int, NozzleState>();
  28. public UdpListenerService(ILogger<UdpListenerService> logger)
  29. {
  30. _logger = logger;
  31. }
  32. public string GetUdpData()
  33. {
  34. return "";
  35. }
  36. public Dictionary<int, NozzleState> GetNozzleState()
  37. {
  38. return g_mNozzleState;
  39. }
  40. public Task StartAsync(CancellationToken cancellationToken)
  41. {
  42. _udpClient = new UdpClient(8080); // 监听8080端口
  43. _logger.LogInformation("开始监听UDP端口 8080");
  44. Task.Run(async () =>
  45. {
  46. while (!cancellationToken.IsCancellationRequested)
  47. {
  48. try
  49. {
  50. var result = await _udpClient.ReceiveAsync(cancellationToken);
  51. var message = Encoding.UTF8.GetString(result.Buffer);
  52. BufferData bd = new BufferData();
  53. bd.type = 0;
  54. bd.buffer = result.Buffer;
  55. bd.endpoint = result.RemoteEndPoint;
  56. bd.udpClient = _udpClient;
  57. GlobalTool.g_dataQueue.Enqueue(bd);
  58. //_logger.LogInformation($"接收到消息: {result.Buffer.ToString()}\r\n");
  59. //byte[] responseData = Encoding.UTF8.GetBytes("Echo: " + message);
  60. //await _udpClient.SendAsync(responseData, responseData.Length, result.RemoteEndPoint);
  61. }
  62. catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested)
  63. {
  64. break;
  65. }
  66. catch (Exception ex)
  67. {
  68. _logger.LogError(ex, "接收UDP数据出错");
  69. }
  70. }
  71. }, cancellationToken);
  72. return Task.CompletedTask;
  73. }
  74. public Task StopAsync(CancellationToken cancellationToken)
  75. {
  76. _udpClient?.Close();
  77. _logger.LogInformation("停止监听UDP端口");
  78. return Task.CompletedTask;
  79. }
  80. }
  81. }