서버프로그래밍/gRPC 미니 프로젝트

C# gRPC 최소 개발환경 구축하기 4(클라이언트 구현)

codehunter 2022. 12. 18. 22:22

메인으로 가기

 

클라이언트는 간단히 gRPC를 이용한 통신만 할 수 있는 세팅으로 구성한다.

폴더 구성은 아래와 같이 한다.

 

gRPC_MINI_Framework/ (이하 gmf로 호칭)

        - Server ...

        - Client
                - protoc (클라이언트와 통신할 프로토파일 모음)
                - gmfClient (실제 클라이언트 프로젝트와 솔루션폴더)

 

그리고 닷넷 솔루션과 닷넷 프로젝트를 구성한다.

..\Client> dotnet new console -o ./gmfClient
..\Client> cd gmfClient
..\Client\gmfClient> dotnet new sln
..\Client\gmfClient> dotnet sln add ./gmfClient.csproj

 

패키지는 서버와 동일하게 설치한다.

VSCode 상에서 proto파일을 기존 프로젝트에 추가하려면 다음과 같은 외부 패키지들이 필요하다. 설치할 NuGet 패키지 는 다음과 같다. (Grpc.Tools는 필요하지 않음). (뒤에 버전정보를 빼면 최신버전으로 설치되는데 2022.12월 기준으로 최신버전은 다음과 같다)

   Grpc (2.46.5) 

   Google.Protobuf (3.21.12) 

   Grpc.Tools (2.51.0) 

..\Client\gmfClient> dotnet list package (이미 설치한게 있는지 확인)
..\Client\gmfClient> dotnet add ./gmfClient.csproj package Grpc 
..\Client\gmfClient> dotnet add ./gmfClient.csproj package Google.Protobuf 
..\Client\gmfClient> dotnet list package (설치된 버전 확인)

 

서버에서 작업한 프로토 파일들을 복사한다.

 

최종 작업폴더 구성은 다음과 같다.

📦Client
  📦gmfClient

      ┣ 📂 protobuf

       ┣ 📜ServerMain.cs
      ┃  ┗ 📜ServerMainGrpc.cs
      ┣ 📜gmfClient.csproj
      ┣ 📜gmfClient.sln
      ┗ 📜Program.cs

 

 

Program.cs

using Grpc.Core;
using System;
using ServerMain;

namespace Client
{
    class Program
    {
        private static ServerMainService.ServerMainServiceClient client;

        static void Main(string[] args)
        {
            try
            {
                Login().GetAwaiter().GetResult();
            }
            catch(Exception ex)
            {
                System.Console.WriteLine(ex);;
            }
        }

        static async Task Login()
        {
            Channel channel = new Channel("127.0.0.1:1234", ChannelCredentials.Insecure);
            client = new ServerMain.ServerMainService.ServerMainServiceClient(channel);

            var result = await client.LoginAsync(new LoginRequest{
                Id = "testuser",
                Passwd = "1234"
            });

            System.Console.WriteLine(result.Result);
        }
    }
}

 

서버를 켜놓고 클라를 실행시켜서 통신을 시작하면 통신이 되는걸 확인할수 있다.