1 2 package io.grpc.examples.reflection; 3 4 import io.grpc.Grpc; 5 import io.grpc.InsecureServerCredentials; 6 import io.grpc.Server; 7 import io.grpc.examples.helloworld.GreeterGrpc; 8 import io.grpc.examples.helloworld.HelloReply; 9 import io.grpc.examples.helloworld.HelloRequest; 10 import io.grpc.protobuf.services.ProtoReflectionService; 11 import io.grpc.stub.StreamObserver; 12 import java.io.IOException; 13 import java.util.concurrent.TimeUnit; 14 import java.util.logging.Logger; 15 16 /** 17 * Server that manages startup/shutdown of a {@code Greeter} server. 18 */ 19 public class ReflectionServer { 20 private static final Logger logger = Logger.getLogger(ReflectionServer.class.getName()); 21 22 private Server server; 23 start()24 private void start() throws IOException { 25 /* The port on which the server should run */ 26 int port = 50051; 27 server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create()) 28 .addService(new GreeterImpl()) 29 .addService(ProtoReflectionService.newInstance()) // add reflection service 30 .build() 31 .start(); 32 logger.info("Server started, listening on " + port); 33 Runtime.getRuntime().addShutdownHook(new Thread() { 34 @Override 35 public void run() { 36 // Use stderr here since the logger may have been reset by its JVM shutdown hook. 37 System.err.println("*** shutting down gRPC server since JVM is shutting down"); 38 try { 39 ReflectionServer.this.stop(); 40 } catch (InterruptedException e) { 41 e.printStackTrace(System.err); 42 } 43 System.err.println("*** server shut down"); 44 } 45 }); 46 } 47 stop()48 private void stop() throws InterruptedException { 49 if (server != null) { 50 server.shutdown().awaitTermination(30, TimeUnit.SECONDS); 51 } 52 } 53 54 /** 55 * Await termination on the main thread since the grpc library uses daemon threads. 56 */ blockUntilShutdown()57 private void blockUntilShutdown() throws InterruptedException { 58 if (server != null) { 59 server.awaitTermination(); 60 } 61 } 62 63 /** 64 * Main launches the server from the command line. 65 */ main(String[] args)66 public static void main(String[] args) throws IOException, InterruptedException { 67 final ReflectionServer server = new ReflectionServer(); 68 server.start(); 69 server.blockUntilShutdown(); 70 } 71 72 static class GreeterImpl extends GreeterGrpc.GreeterImplBase { 73 74 @Override sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver)75 public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) { 76 HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build(); 77 responseObserver.onNext(reply); 78 responseObserver.onCompleted(); 79 } 80 } 81 } 82