支持操做系統:windows、OS X、Linux。實例採用.net、.net core sdk。html
Git (to download the sample code)node
Git (to download the sample code)linux
Git (to download the sample code)git
git clone -b v1.6.x https://github.com/grpc/grpc
C:\Users\YPF\Desktop\grpc
examples/csharp/helloworld
Greeter.sln
從新生成解決方案
項目會自動使用NuGet進行必要的package的安裝。github
> cd GreeterServer/bin/Debug > GreeterServer.exe
> cd GreeterClient/bin/Debug > GreeterClient.exe
打開目錄examples/protos/helloworld.proto
將原來的文件修改成以下並保存:windows
// 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; }
在demo的根目錄(examples/csharp/helloworld
)下執行以下命令:app
packages\Grpc.Tools.1.6.1\tools\windows_x86\protoc.exe -I../../protos --csharp_out Greeter --grpc_out Greeter ../../protos/helloworld.proto --plugin=protoc-gen-grpc=packages/Grpc.Tools.1.6.1/tools/windows_x86/grpc_csharp_plugin.exe
這裏的
Grpc.Tools.1.6.1
這個命令必須是跟項目中使用NuGet安裝的版本一致,不然會報錯。ide
GreeterServer/Program.cs
工具
class GreeterImpl : Greeter.GreeterBase { // Server side handler of the SayHello RPC public override Task<HelloReply> SayHello(HelloRequest request, ServerCallContext context) { return Task.FromResult(new HelloReply { Message = "Hello " + request.Name }); } // Server side handler for the SayHelloAgain RPC public override Task<HelloReply> SayHelloAgain(HelloRequest request, ServerCallContext context) { return Task.FromResult(new HelloReply { Message = "Hello again " + request.Name }); } }
GreeterClient/Program.csvisual-studio
public static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:50051", ChannelCredentials.Insecure); var client = new Greeter.GreeterClient(channel); String user = "you"; var reply = client.SayHello(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + reply.Message); var secondReply = client.SayHelloAgain(new HelloRequest { Name = user }); Console.WriteLine("Greeting: " + secondReply.Message); channel.ShutdownAsync().Wait(); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); }
運行服務
cd GreeterServer/bin/Debug
GreeterServer.exe
運行客戶端
cd GreeterClient/bin/Debug
GreeterClient.exe