Skip to content

Commit 87daf0e

Browse files
author
nmittler
committed
Adding HelloWorld example to grpc-java repo.
1 parent 488f8a9 commit 87daf0e

File tree

6 files changed

+188
-6
lines changed

6 files changed

+188
-6
lines changed

examples/README.md

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,20 @@
11
grpc Examples
22
==============================================
33

4-
In order to run the examples simply execute one of the gradle tasks `routeGuideServer` or
5-
`routeGuideClient`.
4+
In order to run the examples simply execute one of the gradle tasks `routeGuideServer`,
5+
`routeGuideClient`, `helloWorldServer`, or `helloWorldClient`.
66

7-
Assuming you are in the grpc-java root folder you would first start the server by running
7+
For example, say you want to play around with the route guide examples. First you want to start
8+
the server and then have the client connect to it and let the good times roll.
9+
10+
Assuming you are in the grpc-java root folder you would first start the route guide server
11+
by running
812

913
```
1014
$ ./gradlew :grpc-examples:routeGuideServer
1115
```
1216

13-
and in a different terminal window then run the client by typing
17+
and in a different terminal window then run the route guide client by typing
1418

1519
```
1620
$ ./gradlew :grpc-examples:routeGuideClient

examples/build.gradle

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,3 +34,15 @@ task routeGuideClient(type: JavaExec) {
3434
description = "Executes the route guide client."
3535
classpath = sourceSets.main.runtimeClasspath
3636
}
37+
38+
task helloWorldServer(type: JavaExec) {
39+
main = "io.grpc.examples.HelloWorldServer"
40+
description = "Executes the hello world server."
41+
classpath = sourceSets.main.runtimeClasspath
42+
}
43+
44+
task helloWorldClient(type: JavaExec) {
45+
main = "io.grpc.examples.HelloWorldClient"
46+
description = "Executes the hello world client."
47+
classpath = sourceSets.main.runtimeClasspath
48+
}
Lines changed: 58 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,58 @@
1+
package io.grpc.examples;
2+
3+
import io.grpc.ChannelImpl;
4+
import io.grpc.examples.Helloworld.HelloReply;
5+
import io.grpc.examples.Helloworld.HelloRequest;
6+
import io.grpc.transport.netty.NegotiationType;
7+
import io.grpc.transport.netty.NettyChannelBuilder;
8+
9+
import java.util.concurrent.TimeUnit;
10+
import java.util.logging.Level;
11+
import java.util.logging.Logger;
12+
13+
/**
14+
* A simple client that requests a greeting from the {@link HelloWorldServer}.
15+
*/
16+
public class HelloWorldClient {
17+
private static final Logger logger = Logger.getLogger(HelloWorldClient.class.getName());
18+
19+
private final ChannelImpl channel;
20+
private final GreeterGrpc.GreeterBlockingStub blockingStub;
21+
22+
public HelloWorldClient(String host, int port) {
23+
channel =
24+
NettyChannelBuilder.forAddress(host, port).negotiationType(NegotiationType.PLAINTEXT)
25+
.build();
26+
blockingStub = GreeterGrpc.newBlockingStub(channel);
27+
}
28+
29+
public void shutdown() throws InterruptedException {
30+
channel.shutdown().awaitTerminated(5, TimeUnit.SECONDS);
31+
}
32+
33+
public void greet(String name) {
34+
try {
35+
logger.info("Will try to greet " + name + " ...");
36+
HelloRequest req = HelloRequest.newBuilder().setName(name).build();
37+
HelloReply reply = blockingStub.sayHello(req);
38+
logger.info("Greeting: " + reply.getMessage());
39+
} catch (RuntimeException e) {
40+
logger.log(Level.WARNING, "RPC failed", e);
41+
return;
42+
}
43+
}
44+
45+
public static void main(String[] args) throws Exception {
46+
HelloWorldClient client = new HelloWorldClient("localhost", 50051);
47+
try {
48+
/* Access a service running on the local machine on port 50051 */
49+
String user = "world";
50+
if (args.length > 0) {
51+
user = args[0]; /* Use the arg as the name to greet if provided */
52+
}
53+
client.greet(user);
54+
} finally {
55+
client.shutdown();
56+
}
57+
}
58+
}
Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,60 @@
1+
package io.grpc.examples;
2+
3+
import io.grpc.ServerImpl;
4+
import io.grpc.examples.Helloworld.HelloReply;
5+
import io.grpc.examples.Helloworld.HelloRequest;
6+
import io.grpc.stub.StreamObserver;
7+
import io.grpc.transport.netty.NettyServerBuilder;
8+
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+
/* The port on which the server should run */
18+
private int port = 50051;
19+
private ServerImpl server;
20+
21+
private void start() throws Exception {
22+
server = NettyServerBuilder.forPort(port)
23+
.addService(GreeterGrpc.bindService(new GreeterImpl()))
24+
.build().start();
25+
logger.info("Server started, listening on " + port);
26+
Runtime.getRuntime().addShutdownHook(new Thread() {
27+
@Override
28+
public void run() {
29+
// Use stderr here since the logger may has been reset by its JVM shutdown hook.
30+
System.err.println("*** shutting down gRPC server since JVM is shutting down");
31+
HelloWorldServer.this.stop();
32+
System.err.println("*** server shut down");
33+
}
34+
});
35+
}
36+
37+
private void stop() {
38+
if (server != null) {
39+
server.shutdown();
40+
}
41+
}
42+
43+
/**
44+
* Main launches the server from the command line.
45+
*/
46+
public static void main(String[] args) throws Exception {
47+
final HelloWorldServer server = new HelloWorldServer();
48+
server.start();
49+
}
50+
51+
private class GreeterImpl implements GreeterGrpc.Greeter {
52+
53+
@Override
54+
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
55+
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
56+
responseObserver.onValue(reply);
57+
responseObserver.onCompleted();
58+
}
59+
}
60+
}

examples/src/main/java/io/grpc/examples/RouteGuideServer.java

Lines changed: 0 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -88,8 +88,6 @@ public void start() {
8888
.addService(RouteGuideGrpc.bindService(new RouteGuideService(features)))
8989
.build().start();
9090
logger.info("Server started, listening on " + port);
91-
// TODO(simonma): gRPC server should register JVM shutdown hook to shutdown itself, remove this
92-
// after we support that.
9391
Runtime.getRuntime().addShutdownHook(new Thread() {
9492
@Override
9593
public void run() {
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
// Copyright 2015, Google Inc.
2+
// All rights reserved.
3+
//
4+
// Redistribution and use in source and binary forms, with or without
5+
// modification, are permitted provided that the following conditions are
6+
// met:
7+
//
8+
// * Redistributions of source code must retain the above copyright
9+
// notice, this list of conditions and the following disclaimer.
10+
// * Redistributions in binary form must reproduce the above
11+
// copyright notice, this list of conditions and the following disclaimer
12+
// in the documentation and/or other materials provided with the
13+
// distribution.
14+
// * Neither the name of Google Inc. nor the names of its
15+
// contributors may be used to endorse or promote products derived from
16+
// this software without specific prior written permission.
17+
//
18+
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
19+
// "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
20+
// LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
21+
// A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
22+
// OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
23+
// SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
24+
// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
25+
// DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
26+
// THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
27+
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
28+
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
29+
30+
syntax = "proto3";
31+
32+
option java_package = "io.grpc.examples";
33+
34+
package helloworld;
35+
36+
// The greeting service definition.
37+
service Greeter {
38+
// Sends a greeting
39+
rpc SayHello (HelloRequest) returns (HelloReply) {}
40+
}
41+
42+
// The request message containing the user's name.
43+
message HelloRequest {
44+
string name = 1;
45+
}
46+
47+
// The response message containing the greetings
48+
message HelloReply {
49+
string message = 1;
50+
}

0 commit comments

Comments
 (0)