wanshenmean
6 天以前 5171d3f59b89389bf75293afd210cfa6de4ccff7
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
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);
        }
    }
}