Page 55 - MSDN Magazine, September 2019
P. 55
data to users as it comes from the server. In this case, you can attach a SignalR Core endpoint to the client application and notify the UI in real time (see Figure 5).
The following code snippet shows how the client code changes when a SignalR hub is used on top of the gRPC call:
var reply = response.ResponseStream.Current; await _h2hHubContext.Clients
.Client(connId)
.SendAsync("responseReceived", reply.Player1.Name,
reply.Player1.Won, reply.Player2.Name, reply.Player2.Won);
You can check the source code for full details of the solution. Speaking of SignalR, there are a couple of points worth exploring. First, SignalR code is used only by the client application that con- nects to the gRPC service. The hub is injected in the controller of the client application, not in the gRPC service. And second, as far as streaming is concerned, it’s worth noting that SignalR Core also has its own streaming API.
Other Types of gRPC Streams
In this article I focused on server-side gRPC streaming methods, but that isn’t the only option. The gRPC framework also supports client-side streaming methods (multiple requests/one response) and bidirectional streaming (multiple requests/multiple responses). For client-side streaming, the only difference is the use of a IAsyncStreamReader as the input stream in the service method,
as shown in this code:
public override async Task<H2HReply> Multi( IAsyncStreamReader<H2HRequest> requestStream, ServerCallContext context)
{
... }
}
while (await requestStream.MoveNext()) {
var requestPacket = requestStream.Current;
// Some other code here
A bidirectional method will return void and take no parame- ters as it’ll be reading and writing input and output data through input and output streams.
In summary, gRPC is a complete framework to connect two endpoints (client and server) over a binary, flexible and open source protocol. The support you get for gRPC from ASP.NET Core 3.0 is amazing and will improve over time, making now a great time to get started and experiment with gRPC, especially in microservice-to-microservice communication. n
Dino Esposito has authored more than 20 books and 1,000-plus articles in his 25-year career. Author of “The Sabbatical Break,” a theatrical-style show, Esposito is busy writing software for a greener world as the digital strategist at BaxEnergy. Follow him on Twitter: @despos.
thanks to the following Microsoft technical experts for reviewing this article: John Luo, James Newton-King
msdnmagazine.com September 2019 47