using Grpc.Core; using SHH.Contracts.Grpc; namespace SHH.MjpegPlayer { /// /// gRpc 服务宿主管理器 /// 职责:初始化业务处理器、配置并启动 gRpc 监听服务。 /// public static class GrpcServerManager { private static Server? _server; /// /// 启动 gRpc 服务并初始化业务 Handler /// public static void Start() { try { // 1. 显式初始化业务处理器 (确保单例构造函数执行,完成事件订阅) // 必须在服务启动前完成,否则可能丢失首批注册事件 _ = DeviceConfigHandler.Instance; _ = DeviceStatusHandler.Instance; Console.WriteLine("[System] 业务处理器 (Config/Status) 已初始化。"); // 2. 配置 gRpc 服务器 _server = new Server { // 绑定重构后的 GatewayService Services = { GatewayProvider.BindService(new GatewayService()) }, // 监听 9002 端口 Ports = { new ServerPort("[::]", 9002, ServerCredentials.Insecure) } }; // 3. 开启服务 _server.Start(); Console.WriteLine("======================================"); Console.WriteLine("gRpc 服务端启动成功!端口: 9002"); Console.WriteLine("======================================"); } catch (Exception ex) { Console.WriteLine($"[Critical] gRpc 启动失败: {ex.Message}"); // 此处建议记录到本地错误日志文件 } } /// /// 停止服务并释放资源 /// public static void Stop() { if (_server != null) { _server.ShutdownAsync().Wait(); Console.WriteLine("[System] gRpc 服务已停止。"); } } } }