Skip to content

Instantly share code, notes, and snippets.

@davidnadeau
Created July 7, 2022 12:24
Show Gist options
  • Save davidnadeau/055f88cec499a6afb502c9e5f231a271 to your computer and use it in GitHub Desktop.
Save davidnadeau/055f88cec499a6afb502c9e5f231a271 to your computer and use it in GitHub Desktop.
package io.grpc.examples.helloworld;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.StatusRuntimeException;
import io.grpc.stub.StreamObserver;
import java.util.concurrent.TimeUnit;
import java.util.logging.Level;
import java.util.logging.Logger;
public class HelloWorldClient {
private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
private final GreeterGrpc.GreeterStub stub;
/** Construct client for accessing HelloWorld server using the existing channel. */
public HelloWorldClient(ManagedChannel channel) {
stub = GreeterGrpc.newStub(channel);
}
/** Say hello to server. */
public void greet(String name, StreamObserver<HelloReply> responseObserver) {
HelloRequest request = HelloRequest.newBuilder().setName(name).build();
try {
stub.withDeadlineAfter(10, TimeUnit.MILLISECONDS).sayHello(request, responseObserver);
} catch (StatusRuntimeException e) {
logger.log(Level.WARNING, "RPC failed: {0}", e.getStatus());
return;
}
}
public static void main(String[] args) throws Exception {
ManagedChannel channel =
ManagedChannelBuilder.forTarget("localhost:50051").usePlaintext().build();
HelloWorldClient client = new HelloWorldClient(channel);
while (true) {
client.greet("a".repeat(100000), responseObserver);
Thread.sleep(1);
}
}
static StreamObserver<HelloReply> responseObserver =
new StreamObserver<HelloReply>() {
@Override
public void onNext(HelloReply reply) {
}
@Override
public void onError(Throwable t) {
logger.info(t.getMessage());
}
@Override
public void onCompleted() {
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment