/** * A simple client that requests a greeting from the {@link HelloWorldServer}. */ publicclassHelloWorldClient{ privatestaticfinal Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
/** * Greet server. If provided, the first element of {@code args} is the name to use in the * greeting. */ publicstaticvoidmain(String[] args)throws Exception { HelloWorldClient client = new HelloWorldClient("localhost", 50051); try { /* Access a service running on the local machine on port 50051 */ String user = "world"; if (args.length > 0) { user = args[0]; /* Use the arg as the name to greet if provided */ } client.greet(user); } finally { client.shutdown(); } } }
/** * Server that manages startup/shutdown of a {@code Greeter} server. */ publicclassHelloWorldServer{ privatestaticfinal Logger logger = Logger.getLogger(HelloWorldServer.class.getName());
/* The port on which the server should run */ privateint port = 50051; private ServerImpl server;
privatevoidstart()throws Exception { server = NettyServerBuilder.forPort(port) .addService(GreeterGrpc.bindService(new GreeterImpl())) .build().start(); logger.info("Server started, listening on " + port); Runtime.getRuntime().addShutdownHook(new Thread() { @Override publicvoidrun(){ // Use stderr here since the logger may have been reset by its JVM shutdown hook. System.err.println("*** shutting down gRPC server since JVM is shutting down"); HelloWorldServer.this.stop(); System.err.println("*** server shut down"); } }); }
privatevoidstop(){ if (server != null) { server.shutdown(); } }
/** * Main launches the server from the command line. */ publicstaticvoidmain(String[] args)throws Exception { final HelloWorldServer server = new HelloWorldServer(); server.start(); }