UdpServerService.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. using Microsoft.Extensions.Hosting;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Net;
  6. using System.Net.Sockets;
  7. using System.Text;
  8. using System.Threading.Tasks;
  9. namespace EasyTemplate.Service
  10. {
  11. public class UdpServerService : IHostedService
  12. {
  13. private UdpClient udpServer;
  14. private IPEndPoint endPoint;
  15. private CancellationTokenSource cancellationTokenSource;
  16. public event Action<string> OnMessageReceived;
  17. public string data;
  18. public UdpServerService()
  19. {
  20. }
  21. private void DoWork(object state)
  22. {
  23. }
  24. public Task StartAsync(CancellationToken cancellationToken)
  25. {
  26. cancellationTokenSource = new CancellationTokenSource();
  27. endPoint = new IPEndPoint(IPAddress.Any, 10000);
  28. udpServer = new UdpClient(endPoint);
  29. _ = Task.Run(async () =>
  30. {
  31. while (!cancellationTokenSource.Token.IsCancellationRequested)
  32. {
  33. try
  34. {
  35. UdpReceiveResult result = await udpServer.ReceiveAsync();
  36. string message = Encoding.UTF8.GetString(result.Buffer);
  37. data = message;
  38. OnMessageReceived?.Invoke($"Received: {message} from {result.RemoteEndPoint}");
  39. // Echo back
  40. byte[] responseData = Encoding.UTF8.GetBytes("Echo: " + message);
  41. await udpServer.SendAsync(responseData, responseData.Length, result.RemoteEndPoint);
  42. }
  43. catch (ObjectDisposedException)
  44. {
  45. break;
  46. }
  47. catch (Exception ex)
  48. {
  49. OnMessageReceived?.Invoke($"Error: {ex.Message}");
  50. }
  51. }
  52. }, cancellationTokenSource.Token);
  53. return Task.CompletedTask;
  54. }
  55. public Task StopAsync(CancellationToken cancellationToken)
  56. {
  57. cancellationTokenSource?.Cancel();
  58. udpServer?.Close();
  59. return Task.CompletedTask;
  60. }
  61. }
  62. }