Client-Side Implementation of Server Streaming RPC
Explore the client-side implementation of a server streaming RPC in gRPC with Java. Learn how to asynchronously request file contents from a server, handle responses using StreamObserver callbacks, manage synchronization with CountDownLatch, and process error and completion events. This lesson guides you through integrating these concepts within a CLI client, enabling efficient and asynchronous communication in distributed applications.
When users want to read a file, they pass the name of the file and the server address as command line arguments. We will parse the arguments and if certain conditions are met, call the readFile method of the SampleCLIClient class. This method in turn calls the readFile method of the FTPServiceClient class. In this lesson, we show the client-side implementation of the readFile RPC. The client side is implemented in the ftp-service-client module and it is called using the ftp-service-cli-client module.
readFile method in FTPServiceClient class
The ftp-service-client module contains the client implementation of the FTP service. Open the FTPServiceClient class from the src/main/java/io/datajek/ftpservice/client package. We will create a readFile method in this class. The client sends a request to the server with the filename to read. The server responds with the file contents.
The method takes two input parameters:
filenameToRead: This parameter is a string that represents the name of the file we want to read from the server.resultStreamObserver: It is aStreamObserverthat allows the client to receive asynchronous responses from the server. In this case, it is used to handle the server’s response to the read file request.
public void readFile(String filenameToRead, StreamObserver<ReadFileResult> resultStreamObserver) {}
Inside the readFile method, we will send the file name to read as a MetaData message. The message is created in lines 3-5.
public void readFile(String filenameToRead, StreamObserver<ReadFileResult> resultStreamObserver) {MetaData request = MetaData.newBuilder().setName(filenameToRead).build();asyncStub.readFile(request, resultStreamObserver);}
The asyncStub is used to ...