当iOS应用进入后台时,gRPC服务器停止接收请求

时间:2020-10-24 23:09:20

标签: ios swift grpc grpc-swift

我想在我的iOS应用中运行gRPC服务器,而我的应用可能在后台运行了很长时间。当App处于前台模式时,它工作正常,但是在后台模式下,gRPC服务器将不响应任何客户端连接。并且一旦应用回到前台,它将再次工作。

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

任何帮助将不胜感激!

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()
    }
}

0 个答案:

没有答案
相关问题