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