You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

9 月之前
9 月之前
9 月之前
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using DotNetty.Transport.Bootstrapping;
  2. using DotNetty.Transport.Channels;
  3. using Microsoft.Extensions.Hosting;
  4. using Microsoft.Extensions.Logging;
  5. using System;
  6. using System.Collections.Generic;
  7. using System.Linq;
  8. using System.Net;
  9. using System.Text;
  10. using System.Threading.Tasks;
  11. namespace NearCardAttendance.TcpServer
  12. {
  13. public class Server : BackgroundService
  14. {
  15. private readonly ILogger<Server> _logger;
  16. //private readonly IServiceProvider _serviceProvider;
  17. private readonly ServerBootstrap _serverBootstrap;
  18. // private IChannel _serverChannel = default!;
  19. private CancellationTokenSource _tokenSource = null!;
  20. public Server(
  21. ILogger<Server> logger,
  22. ServerBootstrap serverBootstrap,
  23. IServiceProvider serviceProvider)
  24. {
  25. _logger = logger;
  26. //_serviceProvider = serviceProvider;
  27. _serverBootstrap = serverBootstrap;
  28. }
  29. public override Task StartAsync(CancellationToken cancellationToken)
  30. {
  31. _logger.LogInformation("------StartAsync");
  32. _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
  33. return base.StartAsync(cancellationToken);
  34. }
  35. public override Task StopAsync(CancellationToken cancellationToken)
  36. {
  37. _logger.LogInformation("------StopAsync");
  38. _tokenSource.Cancel(); //停止工作线程
  39. return base.StopAsync(cancellationToken);
  40. }
  41. protected override async Task ExecuteAsync(CancellationToken stoppingToken)
  42. {
  43. _logger.LogInformation("DotNetty server starting...");
  44. //var address = new IPEndPoint(IPAddress.Any, 12345);
  45. //IChannel _serverChannel = await _serverBootstrap.BindAsync(address);
  46. string ipAddress = "0.0.0.0";
  47. int port = 16662;
  48. var endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
  49. IChannel _serverChannel = await _serverBootstrap.BindAsync(endPoint);
  50. // _serverChannel.GetAttribute(MessageIdAttribute.Key).Set("SomeRequestId");
  51. //_logger.LogInformation("DotNetty server started on {0}.", address);
  52. _logger.LogInformation("DotNetty server started on {0}.", endPoint);
  53. // Wait until the service is stopped
  54. stoppingToken.WaitHandle.WaitOne();
  55. _logger.LogInformation("DotNetty server stopping...");
  56. // Close the server channel and release resources
  57. await _serverChannel.CloseAsync();
  58. _logger.LogInformation("DotNetty server stopped.");
  59. }
  60. }
  61. }