Server Streaming via gRPC

Reading Time: 2 minutes

In this blog, we will see how we can do Server Streaming via gRPC. In Server Streaming, the client sends only a single request and got multiple responses.

Server Streaming via gRPC

Server streaming RPCs where the client sends a request to the server and gets a stream to read a sequence of messages back. The client reads from the returned stream until there are no more messages. gRPC guarantees message ordering within an individual RPC call.

service GreetService {
    // Server Streaming
    rpc GreetManyTimes(GreetManyTimesRequest) returns (stream GreetManyTimesResponse) {};
}

We will have to use keyword stream before the response to allow multiple responses as stream from the server. When we compile this .proto file , the code will be generated for us and we will have to provide implementations on the client-side and the server-side for the generated API .

Now next step is to setup server and channel. You can go through my blog https://wordpress.com/block-editor/post/blog.knoldus.com/68643 to setup server and channel . Now we will provide implementation on the server side and client side.

Client-side implementation

On client side, we will send a single request to the server according to server-side streaming definition. We have to use synchronous stub i.e generated from compiling the .proto file. The synchronous stub will use the channel so that requests will be sent on a particular server. Below is the code for client-side implementation

 final ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
                .usePlaintext()
                .build();

  private void doServerStreamingCall(ManagedChannel channel) {
// Synchronous stub
        final GreetServiceGrpc.GreetServiceBlockingStub greetClient = GreetServiceGrpc.newBlockingStub(channel);

        // Server Streaming
        // we prepare the request
        final GreetManyTimesRequest greetManyTimesRequest =
                GreetManyTimesRequest.newBuilder()
                        .setGreeting(Greeting.newBuilder().setFirstName("Munander"))
                        .build();

        // we stream the responses (in a blocking manner)
        greetClient.greetManyTimes(greetManyTimesRequest)
                .forEachRemaining(greetManyTimesResponse -> {
                    System.out.println(greetManyTimesResponse.getResult());
                });

    }

Server-side Implementation

At the server side, we will send multiple responses using on the onNext() method. Once all the responses are done , onCompleted() method will be called. Below is the implementation at the server-side

 @Override
    public void greetManyTimes(GreetManyTimesRequest request, StreamObserver<GreetManyTimesResponse> responseObserver) {
        final String firstName = request.getGreeting().getFirstName();

        try {
            for (int i = 0; i < 10; i++) {
                String result = "Hello " + firstName + ", response number: " + i;
                GreetManyTimesResponse response = GreetManyTimesResponse.newBuilder()
                        .setResult(result)
                        .build();

                responseObserver.onNext(response);
                Thread.sleep(1000L);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            responseObserver.onCompleted();
        }
    }

Here we have overridden the API generated from compiling the .proto file and provide the implementation. You can find the source code here https://github.com/Munandermaan/Streaming-via-grpc

Conclusion

Once you go through this blog, you will understand how will you do server streaming in the easiest and precise way.

Reference

https://grpc.io/docs/guides/concepts/

Written by 

Munander is a Software Consultant in Knoldus Software LLP. He has done b.tech from IMS Engineering college, Ghaziabad. He has decent knowledge of C,C++,Java,Angular and Lagom. He always tries to explore new technologies. His hobbies include playing cricket and adventure.