- 参考资料,和详细背景不做赘述。
- 首先定义prop 文件
syntax ="proto3"; package RouteGrpc; service HelloWorld{ rpc SayHello(HellowRequest)returns (ReturnsString){} } message HellowRequest{ string Title=1; string Content=2; } message ReturnsString{ string Content=1; }
- 然后根据prop文件生成对应的客户端和服务端的代码(这里要提前准备protoc.exe和grpc_csharp_plugin.exe)
tools\protoc.exe -I protos --csharp_out out HelloGrpc.proto --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe //-I 工作目录 // --grpc_out 第一个参数是表示输出文件目录 第二个参数表示 描述文件名称(protobuf文件) // --csharp_out 和grpc_out 参数相同 //--plugin= 表示输出c#的插件 tools\protoc.exe -I protos --grpc_out outgrpc HelloGrpc.proto --plugin=protoc-gen-grpc=tools\grpc_csharp_plugin.exe //服务相关
- 生成之后服务端实现Sayhellow相关方法
public class HelloService:HelloWorld.HelloWorldBase { public override Task<ReturnsString> SayHello(HellowRequest request, ServerCallContext context) { return Task.FromResult(new ReturnsString { Content = "Hello " + request.Title +"端口9007"}); } }
- 最终客户端和服务端代码(一共有四种RPC 这里只实现最简单的那种其它类似)
namespace Service { class Program { const int Port = 9007; static void Main(string[] args) { Server server = new Server { Services = { HelloWorld.BindService(new HelloService()) }, Ports = { new ServerPort("localhost", Port, ServerCredentials.Insecure) } }; server.Start(); Console.WriteLine("RouteGuide server listening on port " + Port); Console.WriteLine("Press any key to stop the server..."); Console.ReadKey(); server.ShutdownAsync().Wait(); } } }
namespace Client { class Program { static void Main(string[] args) { Channel channel = new Channel("127.0.0.1:9007", ChannelCredentials.Insecure); var client = new HelloWorld.HelloWorldClient(channel); var retrunstr = client.SayHello(new HellowRequest() { Title = "this is message", Content = "this is content" }); //var retrunstr = await client.SayHelloAsync(new HellowRequest() { Title = "this is message", Content = "this is content" }); Console.WriteLine("来自" + retrunstr.Content); channel.ShutdownAsync().Wait(); Console.WriteLine("任意键退出..."); Console.ReadKey(); } } }
- 项目结构
netcore 实现一个简单的Grpc 服务端和客户端
猜你喜欢
转载自www.cnblogs.com/chongyao/p/10683062.html
今日推荐
周排行