본문 바로가기
프로그래밍

2. gRPC Dart 샘플 프로젝트 설치

by YuminK 2022. 4. 10.

 

https://grpc.io/docs/languages/dart/quickstart/

 

기본적으로 Flutter와 Dart는 연결된 상태라고 가정하고 시작합니다.

 

 

GitHub - grpc/grpc-dart: The Dart language implementation of gRPC.

The Dart language implementation of gRPC. Contribute to grpc/grpc-dart development by creating an account on GitHub.

github.com

다트 언어로 작성된 예제 파일을 다운 받아 줍니다. 

 

helloworld 프로젝트를 열어고 Dart SDK 경로가 연결되지 않은 경우, Settings에서 작업을 해줍니다. 

// Run the Example
dart pub get

// Run the server
dart bin/server.dart 

// from another terminal, run the client
dart bin/client.dart

 

Proto 파일 변경하기

1. dart pub global activate protoc_plugin

protoc_plugin을 설치해줍니다.

 

2. protoc(IDL컴파일러)가 다운이 되어 있어야 합니다.

https://github.com/protocolbuffers/protobuf/releases

protoc-3.20.0-win64.zip

 

해당 경로에서 protoc를 다운을 받고 압축을 풀은 다음에 bin 파일까지의 경로를 복사하고 환경변수 Path에 편집 눌러서 해당 경로를 추가합니다.

 

protoc 동작 확인

 

예제에서 하는 대로 SayHelloAgain을 추가합니다.

// The greeting service definition.
service Greeter {
  // Sends a greeting
  rpc SayHello (HelloRequest) returns (HelloReply) {}
  // Sends another greeting
  rpc SayHelloAgain (HelloRequest) returns (HelloReply) {}
}

// The request message containing the user's name.
message HelloRequest {
  string name = 1;
}

// The response message containing the greetings
message HelloReply {
  string message = 1;
}

 

cmd -> 프로젝트 폴더로 이동하여 다음 명령어를 실행합니다. 

protoc --dart_out=grpc:lib/src/generated -Iprotos protos/helloworld.proto

코드가 변경되어 있다.

서버 변경

bin/server.dart를 열어서 SayHelloAgain() 메소드를 GeeterService에 추가합니다.

class GreeterService extends GreeterServiceBase {
  @override
  Future<HelloReply> sayHello(ServiceCall call, HelloRequest request) async {
    return HelloReply()..message = 'Hello, ${request.name}!';
  }

  @override
  Future<HelloReply> sayHelloAgain(ServiceCall call, HelloRequest request) async {
    return HelloReply()..message = 'Hello again, ${request.name}!';
  }
}

클라이언트 변경

bin/client.dart를 열어서 SayHelloAgain()을 호출합니다.

Future<void> main(List<String> args) async {
  final channel = ClientChannel(
    'localhost',
    port: 50051,
    options: const ChannelOptions(credentials: ChannelCredentials.insecure()),
  );
  final stub = GreeterClient(channel);

  final name = args.isNotEmpty ? args[0] : 'world';

  try {
    var response = await stub.sayHello(HelloRequest()..name = name);
    print('Greeter client received: ${response.message}');
    response = await stub.sayHelloAgain(HelloRequest()..name = name);
    print('Greeter client received: ${response.message}');
  } catch (e) {
    print('Caught error: $e');
  }
  await channel.shutdown();
}

 

업데이트된 내용 실행하기

// Run the server
dart bin/server.dart 

// from another terminal, run the client with a nickname
dart bin/client.dart Alice

// output
Greeter client received: Hello, Alice!
Greeter client received: Hello again, Alice!

 

What’s next

댓글