Implement the client in Java
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.javapackage 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 packagegrpclab-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.
Launch the CalculatorServer in the background:
java -cp target/grpclab-1-jar-with-dependencies.jar cslab.grpclab.CalculatorServer &Launch the CalculatorClient:
java -cp target/grpclab-1-jar-with-dependencies.jar cslab.grpclab.CalculatorClient You should see the following output from CalculatorClient:
JavaClient: The result of 1.000000 + 1.000000 = 2.000000
JavaClient: The result of 3.000000 x 2.000000 = 6.000000You can kill the CalculatorServer by using command:
kill %1Last updated
Was this helpful?