0

我想在我的 iOS 应用程序中运行一个 gRPC 服务器,而我的应用程序可能在后台运行了很长时间。App 在前台模式下可以正常工作,但在后台模式下,gRPC Server 不会响应任何 Client 连接。一旦 App 回到前台,它将再次工作。

如果我在主线程上启动服务器,一切正常。但我不想阻塞我的主线程。

任何帮助将不胜感激!

class ViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Move to a background thread to do some long running work
        DispatchQueue.global(qos: .userInitiated).async {
            self.startServer()
        }
        
    }
    
    func startServer() {
        let group = MultiThreadedEventLoopGroup(numberOfThreads: 2)
        defer {
          try! group.syncShutdownGracefully()
        }

        // Start the server and print its address once it has started.
        let server = Server.insecure(group: group)
          .withServiceProviders([GreeterProvider()])
          .bind(host: "0.0.0.0", port: 53442)
        
        server.map {
            $0.channel.localAddress
        }.whenSuccess { address in
          print("server started on port \(address!.port!)")
        }
        // Wait on the server's `onClose` future to stop the program from exiting.
        _ = try! server.flatMap {
            $0.onClose
        }.wait()
    }
}
4

0 回答 0