| 1 |
// Copyright (C) 2023 The Qt Company Ltd. |
| 2 |
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GFDL-1.3-no-invariants-only |
| 3 |
|
| 4 |
/*! |
| 5 |
\example magic8ball |
| 6 |
\ingroup qtgrpc-examples |
| 7 |
\examplecategory {Networking} |
| 8 |
\meta tag {network,protobuf,grpc} |
| 9 |
\title Magic 8 Ball |
| 10 |
|
| 11 |
\brief Creating a HTTP2 connection between a Qt \gRPC client and a C++ \gRPC server. |
| 12 |
|
| 13 |
Magic 8 ball sends a question to a server and displays the received answer: |
| 14 |
\image magic8ballScreenshot.webp "Magic 8 ball example screenshot" |
| 15 |
|
| 16 |
The example code includes the following components: |
| 17 |
\list |
| 18 |
\li \c magic8ball Qt \gRPC client application that uses |
| 19 |
the \l {qt_add_protobuf}{qt_add_protobuf()} and |
| 20 |
\l {qt_add_grpc}{qt_add_grpc()} |
| 21 |
CMake functions for message and service Qt code generation. |
| 22 |
\li \c server application that calls C++ \gRPC plugin |
| 23 |
for generating server code and implementing simple server |
| 24 |
logic. |
| 25 |
\endlist |
| 26 |
|
| 27 |
\note you need the C++ \gRPC plugin installed. |
| 28 |
Find details here: \l {Module prerequisites} |
| 29 |
|
| 30 |
Both components use generated messages from the protobuf schema described in the |
| 31 |
\c {exampleservice.proto} file: |
| 32 |
\quotefromfile magic8ball/proto/exampleservice.proto |
| 33 |
\skipto syntax = "proto3"; |
| 34 |
\printuntil |
| 35 |
|
| 36 |
The \gRPC client is defined as a QML object \b{which is available after the code is compiled}. |
| 37 |
\snippet magic8ball/Main.qml exampleServiceClient |
| 38 |
|
| 39 |
The client service connects to the \c localhost with port \c {50051}, which is specified in the |
| 40 |
\gRPC channel options: |
| 41 |
\snippet magic8ball/Main.qml channelOptions |
| 42 |
|
| 43 |
And sends a request to the server part: |
| 44 |
\quotefromfile magic8ball/Main.qml |
| 45 |
\snippet magic8ball/Main.qml requestAnswerFunction |
| 46 |
\dots 8 |
| 47 |
\snippet magic8ball/Main.qml requestAnswerFunctionBody |
| 48 |
|
| 49 |
\c answerMethod is a \gRPC method that the client calls. It has four parameters: the request |
| 50 |
object, a finish callback function, an error callback function and a |
| 51 |
\l {GrpcCallOptions} object. |
| 52 |
|
| 53 |
Click the \uicontrol {Ask} button to send the request to the magic8ball server. |
| 54 |
|
| 55 |
\note You have to run the server in parallel with the client application. |
| 56 |
|
| 57 |
The \c server application chooses a random answer from the list of answers and sends |
| 58 |
the data to the client's port. It also checks that the request contains a non empty field |
| 59 |
\c question. If the field is empty, it returns a \c StatusCode::INVALID_ARGUMENT |
| 60 |
\snippet magic8ball/server/main.cpp answerMethod |
| 61 |
|
| 62 |
After receiving a response, the client application shows the answer. |
| 63 |
*/ |