如何调试Swift gRPC客户端与Node.js服务端的本地连接问题
gRPC Node.js服务端与Swift客户端连接问题排查
我正在使用gRPC实现服务端与客户端的通信,服务端基于Node.js,客户端基于Swift。参照gRPC Swift官方教程构建Swift客户端,但无法与本地的Node.js服务端建立连接,希望获取调试方案。
我已通过Postman验证Node.js服务端可正常工作,以下是我的代码,烦请帮忙排查是否存在疏漏:
func prepareGrpc() { let group = PlatformSupport.makeEventLoopGroup(loopCount: 1) defer { try? group.syncShutdownGracefully() } do { let channel = try GRPCChannelPool.with( target: .host("localhost", port: 50051), transportSecurity: .plaintext, eventLoopGroup: group ) client = BookStorePackage_BookAsyncClient(channel: channel) } catch { print("Can't prepare grpc") } } func createBook(id: Int32, bookName: String) async throws { do { let book: BookStorePackage_BookItem = .with { $0.id = id $0.book = bookName } let feature = try await client?.createBook(book) guard let created_book = feature else { print("Failed creating book") return } print("Created book with id: \(created_book.id), name: \(created_book.book)") } catch { print("Error in creating a book") } }
更新
修改后的代码可运行,但出现如下错误,我不确定是否应该每次调用都打开和关闭连接,还是保持连接长期开启:
错误信息:
2023-07-02 13:09:00.936066-0700 bookStore[81602:30021510] [connection] nw_socket_handle_socket_event [C1.1.1:1] Socket SO_ERROR [61: Connection refused]
修改后的代码:
func createBook(id: Int32, bookName: String) async throws { let group = PlatformSupport.makeEventLoopGroup(loopCount: 1) // Make sure the group is shutdown when we're done with it. defer { try! group.syncShutdownGracefully() } // Configure the channel, we're not using TLS so the connection is `insecure`. let channel = try GRPCChannelPool.with( target: .host("localhost", port: 50051), transportSecurity: .plaintext, eventLoopGroup: group ) defer { print("Closing the connection") try! channel.close().wait() } let bookClient = BookStorePackage_BookAsyncClient(channel: channel) let book: BookStorePackage_BookItem = .with { $0.id = id $0.book = bookName } do { let bookResponse = try await bookClient.createBook(book) print("Book response received: \(bookResponse.book) with \(bookResponse.id)") } catch { print("Book response failed: \(error)") } }
内容的提问来源于stack exchange,提问作者Charles Simms
相关产品推荐
相关产品推荐

