Last active
September 10, 2019 04:22
-
-
Save KKcorps/49ec338faeb8e8f6d12f0cc85a86ee4a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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