We now write a simple Java client program to call the CalculatorService.
Create CalculatorClient.java in src/main/cslab/grpclab:
cd ~/grpclab
nano src/main/java/cslab/grpclab/CalculatorClient.java
CalculatorClient.java
package cslab.grpclab;
import io.grpc.Channel;
import io.grpc.ManagedChannelBuilder;
public class CalculatorClient {
public static void main(String[] args){
//Create a connection to `CalculatorServer`
Channel channel = ManagedChannelBuilder.forAddress("127.0.0.1", 8980)
.usePlaintext() // disable TLS
.build();
//Create a stub of Calculator service for invoking the method of Calculator service later on
CalculatorGrpc.CalculatorBlockingStub stub = CalculatorGrpc.newBlockingStub(channel);
// Calculate "1 + 1" by calling the CalculatorService
float a = 1;
float b = 1;
//Create the `CalculationRequest` object and set the value of `a` and `b`
CalculatorOuterClass.CalculationRequest request = CalculatorOuterClass.CalculationRequest.newBuilder()
.setA(a)
.setB(b)
.build();
//Invoking the `sum` function of `CalculatorService` through the stub
CalculatorOuterClass.CalculationRespond respond = stub.sum(request);
System.out.println(String.format("JavaClient: The result of %f + %f = %f", a, b, respond.getResult()));
// Calculate "3 x 2" by calling the CalculatorService
a = 3;
b = 2;
request = CalculatorOuterClass.CalculationRequest.newBuilder()
.setA(a)
.setB(b)
.build();
respond = stub.product(request);
System.out.println(String.format("JavaClient: The result of %f x %f = %f", a, b, respond.getResult()));
}
}
Compile your program
Again we need to compile our code into the JAR. Execute the following command.
mvn package
grpclab-1-jar-with-dependencies.jar will be generated under target which contains the bytecode of your program and dependency libraries.
Test your program
Now we have the CalculatorServer and CalculatorClient. We can test our programs.