C# 에서 gRPC 사용하기
C# 에서 gRPC 사용하기
gRPC란 ?
gRPC는 Google 에서 개발한 고성능 오픈소스 RPC(Remote Procedure Call) 프레임워크입니다. 서로 다른 시스템 간 통신을 마치 로컬 함수 호출처럼 처리할 수 있게 해줍니다.
- HTTP/2 기반 으로 빠른 전송과 스트리밍 지원
- Protocol Buffers(proto) 를 사용한 이진 직렬화로 데이터 전송 효율 극대화
- 다양한 언어 지원 (C#, Java, Go, Python 등)
gRPC와 REST의 차이
| 항목 | gPRC | REST |
|---|---|---|
| 전송 프로토콜 | HTTP/2 | HTTP/1.1 |
| 데이터 포맷 | Protocol Buffers (Binary) | JSON (Text |
| 속도 | 빠름 | 상대적으로 느림 |
| 스트리밍 | 지원 (양방향도 가능) | 제한적 |
| 계약 기반 | 예(proto 파일) | 보통 없음 |
작동 원리 요약
.proto파일로 서비스 및 메세지 정의- 코드 자동 생성 (서버/클라이언트)
- 클라이언트는 서버의 메서드를 로컬 메서드처럼 호출
실습: gRPC 서버 만들기 (Visual Studio 기준)
### 1. gRPC 프로젝트 생성
- Visual Studio → 새 프로젝트 → gRPC 서비스 선택
- 프로젝트명:
GrpcServer - .NET 6 이상 사용
### 2. 기본 구조 설명
Protos/greet.proto: 기본 proto 정의 파일Services/GreeterService.cs: gRPC 메서드 구현체
### 3. greet.proto 내용
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
syntax = "proto3";
option csharp_namespace = "GrpcServer";
package greet;
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
추후 코드에서 name 은 Name 으로 message 는 Message 로 카멀케이싱으로 변경되어 사용됨
### 4. GreeterService.cs
1
2
3
4
5
6
7
8
9
10
public class GreeterService : Greeter.GreeterBase
{
public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context)
{
return Task.FromResult(new HelloReply
{
Message = "Hello " + request.Name
});
}
}
### 5. Program.cs 수정
1
2
app.MapGrpcService<GreeterService>();
app.MapGet("/", () => "gRPC 서버 실행 중");
수정 안해도 무방함.
### 6. launchSettings.json 확인
1
"applicationUrl": "https://localhost:7066;http://localhost:5169"
- 클라이언트는 https://localhost:7066 로 연결해야 함
WPF 에서 gRPC 클라이언트 만들기
### 1. WPF 프로젝트 생성
- Visual Studio → 새 프로젝트 →WPF App 선택
- 이름:
GrpcWpfClient
### 2. Nuget 패키치 설치
Grpc.Net.ClientGoogle.ProtobufGrpc.Tools
### 3. greet.proto 복사 & csproj 설정
Protos/greet.proto 추가 후 .csproj 에:
1
2
3
<ItemGroup>
<Protobuf Include="Protos\greet.proto" GrpcServices="Client" />
</ItemGroup>
### 4. MainWindow.xaml
1
2
3
4
5
<StackPanel Margin="20">
<TextBox x:Name="NameTextBox" Height="30" />
<Button Content="전송" Click="OnSendClick" Height="30" />
<TextBlock x:Name="ResponseTextBlock" FontSize="14" />
</StackPanel>
### 5. MainWindow.xaml.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
private async void OnSendClick(object sender, RoutedEventArgs e)
{
try
{
var name = NameTextBox.Text;
var request = new HelloRequest { Name = name };
var reply = await _client.SayHelloAsync(request);
ResponseTextBlock.Text = reply.Message;
}
catch (Exception ex)
{
ResponseTextBlock.Text = $"오류: {ex.Message}";
}
}
## 실행 결과
- 사용자 입력:
홍길동 - 출력:
Hello 홍길동
## 개발 팁
- 인증서 오류 시:
1
dotnet dev-certs https --trust
- HTTP로 테스트하고 싶다면:
1
AppContext.SetSwitch("System.Net.Http.SocketsHttpHandler.Http2UnencryptedSupport", true);
## 마무리 gRPC는 빠르고 효율적인 통신을 위한 강력한 대응입니다. 특히 WPF 와 같은 클라이언트 앱에서 백엔드와 통신할 때, REST보다 훨씬 가볍고 빠르게 동작합니다.
이 기사는 저작권자의 CC BY 4.0 라이센스를 따릅니다.