매직 8 볼
Qt 클라이언트와 C++ 서버 사이에 HTTP2 연결 생성하기 gRPC™ 클라이언트와 C++ gRPC 서버 사이에 HTTP2 연결을 생성합니다.
매직 8볼은 서버로 질문을 보내고 수신된 답변을 표시합니다:
예제 코드에는 다음 구성 요소가 포함되어 있습니다:
magic8ball
메시지 및 서비스 Qt 코드 생성을 위해 qt_add_protobuf() 및 qt_add_grpc() CMake 함수를 사용하는 Qt gRPC 클라이언트 어플리케이션.server
서버 코드를 생성하고 간단한 서버 로직을 구현하기 위해 C++ gRPC 플러그인을 호출하는 애플리케이션.
참고: C++ gRPC 플러그인이 설치되어 있어야 합니다. 자세한 내용은 여기에서 확인하세요: 모듈 전제 조건
두 컴포넌트 모두 exampleservice.proto
파일에 설명된 프로토뷰 스키마에서 생성된 메시지를 사용합니다:
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(); };
응답을 받은 후 클라이언트 애플리케이션은 답을 표시합니다.
© 2025 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.