using Microsoft.Extensions.Hosting;
|
using Microsoft.Extensions.Options;
|
|
namespace WIDESEAWCS_Tasks.SocketServer
|
{
|
/// <summary>
|
/// Socket 服务器后台主机服务
|
/// </summary>
|
/// <remarks>
|
/// 实现 IHostedService 接口,作为 ASP.NET Core 的后台服务运行。
|
/// 负责在应用启动时启动 Socket 服务器,停止时关闭服务器。
|
/// </remarks>
|
public class SocketServerHostedService : IHostedService
|
{
|
/// <summary>
|
/// TCP Socket 服务器实例
|
/// </summary>
|
private readonly TcpSocketServer _server;
|
|
/// <summary>
|
/// Socket 服务器配置选项
|
/// </summary>
|
private readonly SocketServerOptions _options;
|
|
/// <summary>
|
/// 构造函数
|
/// </summary>
|
/// <param name="server">TCP Socket 服务器实例</param>
|
/// <param name="options">配置选项</param>
|
public SocketServerHostedService(TcpSocketServer server, IOptions<SocketServerOptions> options)
|
{
|
_server = server;
|
_options = options.Value;
|
}
|
|
/// <summary>
|
/// 启动 Socket 服务器
|
/// </summary>
|
/// <remarks>
|
/// 如果配置中服务器被禁用(Enabled=false),则不启动。
|
/// </remarks>
|
/// <param name="cancellationToken">取消令牌</param>
|
/// <returns>启动任务</returns>
|
public Task StartAsync(CancellationToken cancellationToken)
|
{
|
// 检查服务器是否启用
|
if (!_options.Enabled)
|
{
|
return Task.CompletedTask;
|
}
|
|
// 启动服务器
|
return _server.StartAsync(cancellationToken);
|
}
|
|
/// <summary>
|
/// 停止 Socket 服务器
|
/// </summary>
|
/// <param name="cancellationToken">取消令牌</param>
|
/// <returns>停止任务</returns>
|
public Task StopAsync(CancellationToken cancellationToken)
|
{
|
return _server.StopAsync(cancellationToken);
|
}
|
}
|
}
|