環境の構成
1. Dart SDK または Flutter SDK をインストールし、環境変数を構成します
。 2. protobuf をインストールします。
brew install protobuf
3.protoc_pluginをインストールする
pub global activate protoc_plugin
4. bash_profile の下に追加します (M1 の場合は、zshrc にある必要があります)
export PATH="$PATH":"$HOME/.pub-cache/bin"
5. 開発には IDEA を使用しています。.proto ファイルを編集しやすくするために、Protocol Buffer Editor というプラグインをインストールできます。
6.Dart プロジェクト、pusepc.yaml に依存関係を追加します。
dependencies:
protobuf: ^2.0.0
grpc: ^3.0.0
デモ
1. ファイルの作成と生成.
lib ディレクトリに .proto ファイルを作成します
構造.png
2.プロトファイルの書き込み
syntax = "proto3";
package helloworld;
service Greeter{
rpc SayHello(HelloRequest) returns (HelloReply){}
}
message HelloRequest{
string name = 1;
}
message HelloReply{
string message = 1;
}
3. lib ディレクトリに、後で生成するファイルを保存するための新しい src/generated フォルダーを作成します。
4. ファイルの生成
(1) cd プロジェクトを lib ファイルにコピーします
cd /Users/second/Desktop/dev/XXX项目名XXX/lib
(2) プロト生成
protoc --dart_out=grpc:src/generated -Iprotos protos/helloworld.proto
其中:
src/generated:表示lib下存放生成文件的路径
Iprotos:I+编辑的.proto文件文件夹路径
protos/helloworld.proto:表示lib下存放编写.proto文件的路径
このようにして、対応するファイルが生成されたフォルダーに生成されます。
helloworld.pbjson.dart
helloworld.pbgrpc.dart
helloworld.pbenum.dart
helloworld.pb.dart
5. 電話をかける
import 'package:grpc/grpc.dart';
import 'package:grpc_learning/src/generated/helloworld.pbgrpc.dart';
void main() async {
final channel = ClientChannel(
'localhost',
port: 50051,
options: ChannelOptions(
credentials: ChannelCredentials.insecure(),
codecRegistry:
CodecRegistry(codecs: const [GzipCodec(), IdentityCodec()]),
),
);
final stub = GreeterClient(channel);
final name = 'world';
try {
final response = await stub.sayHello(HelloRequest()..name = name);
print('Greeter client received: ${response.message}');
} catch (e) {
print('error = ${e.toString()}');
}
await channel.shutdown();
}
6. 走る
分别运行客户端和服务端,使用dart server.dart和dart client.dart来执行。