gRPC .NET Core跨平台学习

前些天发布gRPC C# 学习,在.NET Framework 中使用gRPC ,今天来学习 .NET Core gRPC。

gRPC 的.NET Core 包在NuGet 上发布了,结合.NET Core 实现gRPC 完美跨平台。

本篇主要讲解 .NET Core 版gRPC客户端运行在Ubuntu系统上,与局域网内的服务端通信。

下面我们来正式开始。

在之前的代码基础开发.NET Core版。

本文运行环境:

服务端:WIN10 x64

客户端:Ubuntu 14.04

添加.NET Core版gRPC Client

首先我们打开之前的gRPCDemo 代码,GitHub:https://github.com/linezero/Blog/tree/master/gRPCDemo 。

添加一个.NET Core 控制台应用 gRPCNETCoreClient

然后在 gRPCNETCoreClient 项目上添加引用:

Install-Package Grpc -Pre

移植传统类库至.NET Core类库

安装好Grpc 以后我们就可以来移植类库了,这里我们首先创建一个gRPCNETCoreDemo Class Library。

新建好以后我们将 project.json 文件更改为如下:

{
  "version": "1.0.0-*",
  "frameworks": {
    "net452": {
      "dependencies": {
        "Grpc": "1.0.0",
        "Grpc.Core": "1.0.0",
        "Google.Protobuf": "3.0.0",
        "System.Interactive.Async": "3.0.0"
      }
    },
    "netstandard1.6": {
      "imports": "dnxcore50",
      "dependencies": {
        "NETStandard.Library": "1.6.0",
        "Grpc": "1.0.1-pre1",
        "Grpc.Core": "1.0.1-pre1",
        "Google.Protobuf": "3.1.0",
        "System.Interactive.Async": "3.1.0-rc"
      }
    }
  }
}

这样类库就能支持.NET Framework 4.5.2 以及 .NET Core。

这里我省略了生成代码,直接将gRPCDemo 中的类复制过来。然后gRPCNETCoreClient 添加gRPCNETCoreDemo 引用。

gRPCNETCoreClient 中Program.cs 添加如下代码,基本上和上篇代码一致,新增了控制台编码输出格式。

    public class Program
    {
        public static void Main(string[] args)
        {
            Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);

            Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure);

            var client = new gRPC.gRPCClient(channel);
            var reply = client.SayHello(new HelloRequest { Name = "LineZero .NET Core Client" });
            Console.WriteLine("来自" + reply.Message);

            channel.ShutdownAsync().Wait();
            Console.WriteLine("任意键退出...");
            Console.ReadKey();
        }
    }

代码编写好以后,我们来执行gRPCServer ,然后使用dotnet run 执行 gRPCNETCoreClient。

成功通信,证明支持.NET Core。 

发布至Ubuntu系统运行

下面将gRPCNETCoreClient 发布至Ubuntu系统跨平台运行。

代码绑定ip需要稍作调整。

查看本地ip 是多少,将gRPCServer 中的localhost 改成本地ip ,并将 Client的127.0.0.1 也改成本地ip。

发布 gRPCNETCoreClient

dotnet publish 

将发布后的目录复制到 Ubuntu 系统。

下面先在本地启动Server  ,然后在Ubuntu系统执行Client 。

成功在Ubuntu 系统上通信,这里服务端是运行在本地,客户端是在另外一台机器上。

gRPC 官网文档:http://www.grpc.io/docs/

protobuf文档:https://developers.google.com/protocol-buffers/docs/overview

 

如果你觉得本文对你有帮助,请点击“推荐”,谢谢。 

posted @ 2016-10-09 09:11  LineZero  阅读(6579)  评论(4编辑  收藏  举报