차량
Qt 클라이언트와 C++ 서버 사이의 두 스레드 연결 관리 gRPC™ 클라이언트와 C++ gRPC 서버 사이의 두 스레드 연결을 관리합니다.
이 예제는 gRPC 서버에서 전송한 데이터를 표시하는 차량 대시보드를 시뮬레이션합니다.
예제 코드에는 다음과 같은 구성 요소가 있습니다:
vehicle_client
메시지 및 서비스 Qt 코드 생성을 위해 qt_add_protobuf() 및 qt_add_grpc() CMake 함수를 사용하는 Qt gRPC 클라이언트 애플리케이션.vehicle_server
서버 코드를 생성하고 간단한 서버 로직을 구현하기 위해 C++ gRPC 플러그인을 호출하는 애플리케이션.
참고: C++ gRPC 플러그인이 설치되어 있어야 합니다. 자세한 내용은 여기에서 확인하세요: 모듈 전제 조건
두 컴포넌트 모두 vehicleservice.proto
및 navigationservice.proto
파일에 설명된 프로토뷰 스키마에서 생성된 메시지를 사용합니다.
차량 서비스:
message SpeedMsg { int32 speed = 1; } message RpmMsg { int32 rpm = 1; } message AutonomyMsg { int32 autonomy = 1; } service VehicleService { rpc getSpeedStream(google.protobuf.Empty) returns (stream SpeedMsg) {} rpc getRpmStream(google.protobuf.Empty) returns (stream RpmMsg) {} rpc getAutonomy(google.protobuf.Empty) returns (AutonomyMsg) {} }
내비게이션 서비스:
enum DirectionEnum { RIGHT = 0; LEFT = 1; STRAIGHT = 2; BACKWARD = 3; } message NavigationMsg { int32 totalDistance = 1; int32 traveledDistance = 2; DirectionEnum direction = 3; string street = 4; } service NavigationService { rpc getNavigationStream(google.protobuf.Empty) returns (stream NavigationMsg) {} }
VehicleManager
C++ 싱글톤은 두 개의 QThread 인스턴스를 사용하여 서버와 병렬로 통신합니다. 스레드에는 서로 다른 gRPC 연결 유형이 있습니다. 이 예시에서는 두 가지 유형이 있습니다:
- 서버 스트리밍 RPC 예를 들어, 차량 스레드의 속도 스트림입니다. 두 개의 콜백 함수를 사용합니다: QGrpcServerStream::messageReceived 와 QGrpcOperation::finished
Empty speedRequest; m_streamSpeed = m_client->getSpeedStream(speedRequest); connect(m_streamSpeed.get(), &.QGrpcServerStream::messageReceived, this, [this]() { if(const auto speedResponse = m_streamSpeed->read<SpeedMsg>()) { emit speedChanged(speedResponse->speed()); } }); connect( m_streamSpeed.get(), &QGrpcServerStream::finished, this,[this](const QGrpcStatus &status) { if (!status.isOk()) { auto error = QString("스트림 오류 페칭 속도 %1 (%2)") .arg(status.message()) .arg(QVariant::fromValue(status.code()).toString()); emit connectionError(error); qWarning() << error; return; }}, Qt::SingleShotConnection);
- 단항 RPC RPC
getAutonomy
연산은 단항 RPC입니다. 단일 응답을 반환합니다. QGrpcOperation::finished 신호에만 연결됩니다.자율성 요청 비우기; std::unique_ptr<QGrpcCallReply> autonomyReply = m_client->getAutonomy(autonomyRequest);const auto *autonomyReplyPtr = autonomyReply.get(); connect( autonomyReplyPtr, &.QGrpcCallReply::finished, this,[this, autonomyReply = std::move(autonomyReply)](const QGrpcStatus &status) { if (!status.isOk()) { auto error = QString("자율성 %1 (%2)을 가져오는 호출 오류") .arg(status.message()) .arg(QVariant::fromValue(status.code()).toString()); emit connectionError(error); qWarning() << error; return; } if(const auto autonomyMsg = autonomyReply->read<AutonomyMsg>()) { emit autonomyChanged(autonomyMsg->autonomy()); }} }, Qt::SingleShotConnection);
클라이언트 메인 창 인터페이스는 Main.qml 파일에 정의되어 있습니다. 이 인터페이스는 VehicleManager
C++ 싱글톤의 신호에 사용자 지정 슬롯에 연결하기 위해 QML Connections 유형을 사용합니다:
Connections { target: VehicleManager // This slot will be executed when the VehicleManager::totalDistanceChanged // signal is emitted function onTotalDistanceChanged(distance: int): void { root.totalDistance = distance; } function onSpeedChanged(speed: int): void { root.speed = speed; } function onRpmChanged(rpm: int): void { root.rpm = rpm; } function onTraveledDistanceChanged(distance: int): void { root.traveledDistance = distance; } function onDirectionChanged(direction: int): void { if (direction == VehicleManager.RIGHT) { root.directionImageSource = "qrc:/direction_right.svg"; } else if (direction == VehicleManager.LEFT) { root.directionImageSource = "qrc:/direction_left.svg"; } else if (direction == VehicleManager.STRAIGHT) { root.directionImageSource = "qrc:/direction_straight.svg"; } else { root.directionImageSource = ""; } }
응답을 수신한 후 클라이언트 창은 수신된 데이터로 UI를 업데이트합니다. 이렇게 하면 다른 스레드에서 메시지를 수신하고 시그널을 통해 스레드 안전 방식으로 클라이언트 UI에 메시지를 전송할 수 있습니다.
© 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.