gRPC .Net Core sample with Stream call
Let’s create an application to use gRPC service in .Net Core to get stream of data from the server.Server:
gRPC Server:
In Visual Studio 2019 select ‘Create New Project’.
We will use the gRPC project template to get started. Select the gRPC template and create the project.

New project is created with GreeterService from the template. Let’s leave it here and create our own service.

Add stock.proto for service definition:
GetStockStream returns the stream of StockResponse
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | syntax = "proto3"; option csharp_namespace = "StockFeed"; package stock; service Stock { rpc GetStockStream (StockRequest) returns (stream StockResponse); } message StockRequest { string stockSymbol = 1; } message StockResponse { string stockSymbol = 1; int64 price = 2; } |
Right click project and Edit project file to verify proto file is included for code generation

Let’s create C# service class.
StockService derives the auto generated StockBase class.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public class StockService : Stock.StockBase { public override async Task GetStockStream(StockRequest request, IServerStreamWriter<StockResponse> responseStream, ServerCallContext context) { var count = 0; while (context.CancellationToken.IsCancellationRequested || count < 10) { count++; await Task.Delay(500); var response = new StockResponse { StockSymbol = request.StockSymbol, Price = count * 500 }; await responseStream.WriteAsync(response); } } |
In Startup.cs register the service:

Hit F5, and you can see the server is started:

gRPC Client:
Add new .net Core Console App to create service client.
Add following nuget packages to the client :
- Google.Protobuf
- Grpc.Net.Client
- Grpc.Tools
Copy stock.proto to StockFeedClient project and edit the project file to generate the client code for stock service. Change GrpcServices = “Client” .

In Program.cs add following code make the service call:
class Program
{
static async void Main(string[] args)
{
var channel = GrpcChannel.ForAddress(“https://localhost:5001”);
var client = new Stock.StockClient(channel);
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | class Program { static async Task Main(string[] args) { var channel = GrpcChannel.ForAddress("https://localhost:5001"); var client = new Stock.StockClient(channel); var cts = new CancellationTokenSource(15000); //15 seconds var streamCall = client.GetStockStream(new StockRequest { StockSymbol = "ABC" }, cancellationToken: cts.Token); await foreach (var response in streamCall.ResponseStream.ReadAllAsync(cts.Token)) { Console.WriteLine($"Stock response Symbol {response.StockSymbol} Price: {response.Price}"); } Console.ReadLine(); } } |
Note: If client code is not generated, make any change and save the proto file.
Test
Hit F5 to start the server. Then right click on client project ‘Debug -> Start New Instance’ to start the client.
Following result will be displayed on client console:
