flutter grpc简单实现

配置环境
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 进行开发,可以安装一个叫 Protocol Buffer Editor 的插件,来帮助我们更好地编辑 .proto 文件。
6.Dart 工程,在其pusepc.yaml里添加依赖:

dependencies:
  protobuf: ^2.0.0
  grpc: ^3.0.0

Demo
1.创建并生成文件
在lib目录下创建.proto文件

结构.png


2.编写proto文件

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)生成proto

protoc --dart_out=grpc:src/generated -Iprotos protos/helloworld.proto
其中:
src/generated:表示lib下存放生成文件的路径
Iprotos:I+编辑的.proto文件文件夹路径
protos/helloworld.proto:表示lib下存放编写.proto文件的路径

这样 generated 文件夹下就会生成相应的文件:

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来执行。

猜你喜欢

转载自blog.csdn.net/qq_27981847/article/details/132759772
今日推荐