魔术8号球
在 Qt gRPC™ 客户端与 C++gRPC 服务器之间建立 HTTP/2 连接。
“魔术8号”会向服务器发送问题,并显示收到的答案:

示例代码包含以下组件:
magic8ball一个 QtgRPC 客户端应用程序,该应用程序使用qt_add_protobuf()和qt_add_grpc()CMake 函数来生成消息和服务的 Qt 代码。server该应用程序调用 C++gRPC 插件来生成服务器代码并实现简单的服务器逻辑。
注意:您需要 安装 C++gRPC 插件。详情请参见:模块先决条件
这两个组件都使用由exampleservice.proto 文件中描述的Protobuf模式生成的消息:
syntax = "proto3";
package qtgrpc.examples;
message AnswerRequest {
string question = 1;
}
message AnswerResponse {
string message = 1;
}
service ExampleService {
rpc answerMethod(AnswerRequest) returns (AnswerResponse) {}
}gRPC 客户端被定义为一个 QML 对象,代码编译完成后即可使用。
ExampleServiceClient {
id: grpcClient
channel: grpcChannel.channel
}客户端服务通过端口50051 连接到localhost ,该端口在gRPC 通道选项中指定:
GrpcHttp2Channel {
id: grpcChannel
hostUri: "http://localhost:50051"
// Optionally, you can specify custom channel options here
// options: GrpcChannelOptions {}
}并向服务器端发送请求:
function requestAnswer(question: string): void {
...
root.answerReq.question = question;
grpcClient.answerMethod(root.answerReq, finishCallback, errorCallback, grpcCallOptions);
}answerMethod 是客户端调用的gRPC 方法。它有四个参数:请求对象、完成回调函数、错误回调函数以及GrpcCallOptions 对象。
点击“Ask ”按钮,将请求发送至 magic8ball 服务器。
注意:必须 在运行客户端应用程序的同时运行服务器。
server 应用程序会从答案列表中随机选择一个答案,并将数据发送到客户端的端口。它还会检查请求中是否包含非空的question 字段。如果该字段为空,则返回一个StatusCode::INVALID_ARGUMENT
grpc::Status answerMethod(grpc::ServerContext *, const AnswerRequest *request,
AnswerResponse *response) override
{
if (request->question().empty()) {
std::cerr << "Question is empty" << std::endl;
return grpc::Status(grpc::StatusCode::INVALID_ARGUMENT, "Question is empty");
}
std::cout << "Received question: " << request->question() << std::endl;
response->set_message(getRandomAnswer());
return grpc::Status();
};收到响应后,客户端应用程序会显示该答案。
© 2026 The Qt Company Ltd. Documentation contributions included herein are the copyrights of their respective owners. The documentation provided herein is licensed under the terms of the GNU Free Documentation License version 1.3 as published by the Free Software Foundation. Qt and respective logos are trademarks of The Qt Company Ltd. in Finland and/or other countries worldwide. All other trademarks are property of their respective owners.