| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104 |
- using AntDesign;
- using EasyTemplate.Tool;
- using EasyTemplate.Tool.Entity;
- using Masuit.Tools;
- using Microsoft.AspNetCore.Components;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using OneOf.Types;
- using SqlSugar;
- using System.Globalization;
- using System.Net.Sockets;
- using System.Reflection.Emit;
- using System.Runtime.InteropServices;
- using System.Security.Cryptography;
- using System.Text;
- using System.Xml.Linq;
- using EasyTemplate.Service;
- using static System.Runtime.InteropServices.JavaScript.JSType;
- using Microsoft.Extensions.DependencyInjection;
- namespace EasyTemplate.Service
- {
- public class UdpListenerService : IHostedService
- {
- private readonly ILogger<UdpListenerService> _logger;
- private UdpClient? _udpClient;
- public static List<string> ReceivedMessages { get; } = new();
- public Dictionary<int, NozzleState> g_mNozzleState = new Dictionary<int, NozzleState>();
-
- public UdpListenerService(ILogger<UdpListenerService> logger)
- {
- _logger = logger;
- }
- public string GetUdpData()
- {
- return "";
- }
- public Dictionary<int, NozzleState> GetNozzleState()
- {
- return g_mNozzleState;
- }
- public Task StartAsync(CancellationToken cancellationToken)
- {
- _udpClient = new UdpClient(8080); // 监听8080端口
- _logger.LogInformation("开始监听UDP端口 8080");
- Task.Run(async () =>
- {
- while (!cancellationToken.IsCancellationRequested)
- {
- try
- {
- var result = await _udpClient.ReceiveAsync(cancellationToken);
- var message = Encoding.UTF8.GetString(result.Buffer);
- BufferData bd = new BufferData();
- bd.type = 0;
- bd.buffer = result.Buffer;
- bd.endpoint = result.RemoteEndPoint;
- bd.udpClient = _udpClient;
- GlobalTool.g_dataQueue.Enqueue(bd);
- //_logger.LogInformation($"接收到消息: {result.Buffer.ToString()}\r\n");
- //byte[] responseData = Encoding.UTF8.GetBytes("Echo: " + message);
- //await _udpClient.SendAsync(responseData, responseData.Length, result.RemoteEndPoint);
- }
- catch (ObjectDisposedException) when (cancellationToken.IsCancellationRequested)
- {
- break;
- }
- catch (Exception ex)
- {
- _logger.LogError(ex, "接收UDP数据出错");
- }
- }
- }, cancellationToken);
- return Task.CompletedTask;
- }
- public Task StopAsync(CancellationToken cancellationToken)
- {
- _udpClient?.Close();
- _logger.LogInformation("停止监听UDP端口");
- return Task.CompletedTask;
- }
- }
- }
|