매직 8 볼
Qt gRPC™ 클라이언트와 C++ gRPC 서버 간에 HTTP2 연결을 설정합니다.
매직 8 볼은 서버에 질문을 전송하고 수신된 답변을 표시합니다:

이 예제 코드에는 다음 구성 요소가 포함되어 있습니다:
magic8ball메시지 및 서비스 Qt 코드 생성을 위해 qt_add_protobuf() 및 qt_add_grpc() CMake 함수를 사용하는 Qt XML gRPC 클라이언트 애플리케이션.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
}클라이언트 서비스는 gRPC 채널 옵션에 지정된 포트 50051 을 통해 localhost 에 연결합니다:
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.