Implement the client in Java
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
Test your program
Last updated