小小书童 2017-09-30
支持操作系统:windows、OS X、Linux。实例采用.net、.net core sdk。
Git (to download the sample code)
Git (to download the sample code)
Git (to download the sample code)
git clone -b v1.6.x https://github.com/grpc/grpc
C:\Users\YPF\Desktop\grpc
examples/csharp/helloworld
Greeter.sln
重新生成解决方案
项目会自动使用NuGet进行必要的package的安装。
运行服务
> cd GreeterServer/bin/Debug > GreeterServer.exe
运行客户端
> cd GreeterClient/bin/Debug > GreeterClient.exe
打开目录examples/protos/helloworld.proto
将原来的文件修改为如下并保存:
// 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
)下执行如下命令:
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安装的版本一致,否则会报错。
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.cs
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