This step extends the generated server skeleton code to write a simple server that provides the hello service. This in introduces two new classes
a service implementation GreetingsImpl.java.
a server that hosts the service implementation and allows to accessed over the network: GreetingsServer.java.
GreetingsSImpl.java implements the behaviour we require of our GreetingService. There are a number of important features of gRPC being used here:
public void hello(Helloworld.HelloRequest req,
StreamObserver<Helloworld.HelloReply> responseObserver) {
Helloworld.HelloReply reply = Helloworld.HelloReply.newBuilder().setMessage(
"Hello " + req.getName()).build();
responseObserver.onValue(reply);
responseObserver.onCompleted();
}
GreetingsImpl that implements a generated interface GreetingsGrpc.GreetingsGreetingsGrpc.Greetings declares the method hello that was declared in the proto IDLhello's signature is typesafe:
hello(Helloworld.HelloRequest req, StreamObserver responseObserver)
hello takes two parameters:
Helloworld.HelloRequest: the request
StreamObserver<Helloworld.HelloReply>: a response observer, an interface to be called with the response valueGreetingsServer.java shows the other main feature to required to provde gRPC service; how to allow a service implementation to be accessed from the network.
private void start() throws Exception {
server = NettyServerBuilder.forPort(port)
.addService(GreetingsGrpc.bindService(new GreetingsImpl()))
.build();
server.startAsync();
server.awaitRunning(5, TimeUnit.SECONDS);
}
GreetingsServer that holds a ServerImpl that will run the serverstart method, GreetingServer binds the GreetingsService implementation to a port and begins running itstop method that takes care of shutting down the service and cleaning up when the program exitsThis is the same as before: our client and server are part of the same maven package so the same command builds both.
$ mvn package
We've added simple shell scripts to simplifying running the examples. Now that they are built, you can run the server with.
$ ./run_greetings_server.sh
In another termainal window and confirm that it receives a message.
$ ./run_greetings_client.sh