Skip to content

Instantly share code, notes, and snippets.

@KKcorps
Last active September 10, 2019 04:22
Show Gist options
  • Save KKcorps/49ec338faeb8e8f6d12f0cc85a86ee4a to your computer and use it in GitHub Desktop.
Save KKcorps/49ec338faeb8e8f6d12f0cc85a86ee4a to your computer and use it in GitHub Desktop.
public class Client {
private final ManagedChannel channel;
private final GreeterBlockingStub blockingStub;
private final GreeterStub asyncStub;
public Client(String host, String port){
channel = ManagedChannelBuilder.forAddress(host, port).usePlaintext().build(); //remove .usePlainText for secure connections
blockingStub = GreeterGrpc.newBlockingStub(channel); // use it to make blocking calls
asyncStub = GreeterGrpc.newStub(channel); // or use this to make async calls
}
public void blockingGreet(String name) {
logger.info("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
HelloReply response;
try {
response = blockingStub.sayHello(request);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
logger.info("Greeting: " + response.getMessage());
}
public void asyncGreet(String name) {
StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() {
@Override
public void onNext(HelloReply response) {
logger.info("Greeting: " + response.getMessage());
}
@Override
public void onError(Throwable t) {
Status status = Status.fromThrowable(t);
logger.log(Level.WARNING, "RPC Failed: {0}", status);
}
@Override
public void onCompleted() {
info("Finished Greeting");
}
};
logger.info("Will try to greet " + name + " ...");
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
asyncStub.sayHello(request, responseObserver);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment