|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- using DotNetty.Transport.Bootstrapping;
- using DotNetty.Transport.Channels;
- using Microsoft.Extensions.Hosting;
- using Microsoft.Extensions.Logging;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Net;
- using System.Text;
- using System.Threading.Tasks;
-
- namespace NearCardAttendance.TcpServer
- {
- public class Server : BackgroundService
- {
- private readonly ILogger<Server> _logger;
- private readonly IServiceProvider _serviceProvider;
- private readonly ServerBootstrap _serverBootstrap;
- private IChannel _serverChannel = default!;
- private CancellationTokenSource _tokenSource = null!;
-
-
- public Server(
- ILogger<Server> logger,
- ServerBootstrap serverBootstrap,
- IServiceProvider serviceProvider)
- {
- _logger = logger;
- _serviceProvider = serviceProvider;
- _serverBootstrap = serverBootstrap;
-
- }
- public override Task StartAsync(CancellationToken cancellationToken)
- {
- _logger.LogInformation("------StartAsync");
- _tokenSource = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken);
- return base.StartAsync(cancellationToken);
- }
-
- public override Task StopAsync(CancellationToken cancellationToken)
- {
- _logger.LogInformation("------StopAsync");
- _tokenSource.Cancel(); //停止工作线程
- return base.StopAsync(cancellationToken);
- }
- protected override async Task ExecuteAsync(CancellationToken stoppingToken)
- {
-
- _logger.LogInformation("DotNetty server starting...");
-
- //var address = new IPEndPoint(IPAddress.Any, 12345);
-
- //IChannel _serverChannel = await _serverBootstrap.BindAsync(address);
-
- string ipAddress = "0.0.0.0";
- int port = 16662;
- var endPoint = new IPEndPoint(IPAddress.Parse(ipAddress), port);
- IChannel _serverChannel = await _serverBootstrap.BindAsync(endPoint);
- // _serverChannel.GetAttribute(MessageIdAttribute.Key).Set("SomeRequestId");
-
- //_logger.LogInformation("DotNetty server started on {0}.", address);
- _logger.LogInformation("DotNetty server started on {0}.", endPoint);
-
-
- // Wait until the service is stopped
- stoppingToken.WaitHandle.WaitOne();
-
- _logger.LogInformation("DotNetty server stopping...");
-
- // Close the server channel and release resources
- await _serverChannel.CloseAsync();
- _logger.LogInformation("DotNetty server stopped.");
- }
-
-
- }
- }
|