Skip to content

Commit 6386cda

Browse files
committed
examples:Client and server sharing example
1 parent 99cbdd5 commit 6386cda

File tree

5 files changed

+497
-0
lines changed

5 files changed

+497
-0
lines changed

examples/BUILD.bazel

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,22 @@
11
load("@rules_proto//proto:defs.bzl", "proto_library")
22
load("@io_grpc_grpc_java//:java_grpc_library.bzl", "java_grpc_library")
33

4+
proto_library(
5+
name = "echo_proto",
6+
srcs = ["src/main/proto/echo.proto"],
7+
)
8+
9+
java_proto_library(
10+
name = "echo_java_proto",
11+
deps = [":echo_proto"],
12+
)
13+
14+
java_grpc_library(
15+
name = "echo_java_grpc",
16+
srcs = [":echo_proto"],
17+
deps = [":echo_java_proto"],
18+
)
19+
420
proto_library(
521
name = "helloworld_proto",
622
srcs = ["src/main/proto/helloworld.proto"],

examples/build.gradle

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -216,6 +216,20 @@ task cancellationServer(type: CreateStartScripts) {
216216
classpath = startScripts.classpath
217217
}
218218

219+
task multiplexingServer(type: CreateStartScripts) {
220+
mainClass = 'io.grpc.examples.multiplex.MultiplexingServer'
221+
applicationName = 'multiplexing-server'
222+
outputDir = new File(project.buildDir, 'tmp/scripts/' + name)
223+
classpath = startScripts.classpath
224+
}
225+
226+
task sharingClient(type: CreateStartScripts) {
227+
mainClass = 'io.grpc.examples.multiplex.SharingClient'
228+
applicationName = 'sharing-client'
229+
outputDir = new File(project.buildDir, 'tmp/scripts/' + name)
230+
classpath = startScripts.classpath
231+
}
232+
219233
applicationDistribution.into('bin') {
220234
from(routeGuideServer)
221235
from(routeGuideClient)
@@ -239,5 +253,7 @@ applicationDistribution.into('bin') {
239253
from(keepAliveClient)
240254
from(cancellationClient)
241255
from(cancellationServer)
256+
from(multiplexingServer)
257+
from(sharingClient)
242258
fileMode = 0755
243259
}
Lines changed: 110 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,110 @@
1+
/*
2+
* Copyright 2023 The gRPC Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.grpc.examples.multiplex;
18+
19+
import io.grpc.Grpc;
20+
import io.grpc.InsecureServerCredentials;
21+
import io.grpc.Server;
22+
import io.grpc.examples.echo.EchoGrpc;
23+
import io.grpc.examples.echo.EchoRequest;
24+
import io.grpc.examples.echo.EchoResponse;
25+
import io.grpc.stub.StreamObserver;
26+
import java.util.ArrayList;
27+
import java.util.List;
28+
import java.util.logging.Level;
29+
import java.util.logging.Logger;
30+
import java.util.stream.Collectors;
31+
32+
/**
33+
* Service that echoes back whatever is sent to it.
34+
*/
35+
public class EchoService extends EchoGrpc.EchoImplBase {
36+
private static final Logger logger = Logger.getLogger(EchoService.class.getName());
37+
38+
@Override
39+
public void unaryEcho(EchoRequest request,
40+
StreamObserver<EchoResponse> responseObserver) {
41+
logger.info("Received echo request: " + request.getMessage());
42+
EchoResponse response = EchoResponse.newBuilder().setMessage(request.getMessage()).build();
43+
responseObserver.onNext(response);
44+
responseObserver.onCompleted();
45+
}
46+
47+
@Override
48+
public void serverStreamingEcho(EchoRequest request,
49+
StreamObserver<EchoResponse> responseObserver) {
50+
logger.info("Received server streaming echo request: " + request.getMessage());
51+
EchoResponse response = EchoResponse.newBuilder().setMessage(request.getMessage()).build();
52+
responseObserver.onNext(response);
53+
responseObserver.onCompleted();
54+
}
55+
56+
@Override
57+
public StreamObserver<EchoRequest> clientStreamingEcho(
58+
final StreamObserver<EchoResponse> responseObserver) {
59+
return new StreamObserver<EchoRequest>() {
60+
List<String> requestList = new ArrayList<>();
61+
62+
@Override
63+
public void onNext(EchoRequest request) {
64+
logger.info("Received client streaming echo request: " + request.getMessage());
65+
requestList.add(request.getMessage());
66+
}
67+
68+
@Override
69+
public void onError(Throwable t) {
70+
logger.log(Level.WARNING, "echo stream cancelled or had a problem and is no longer usable " + t.getMessage());
71+
responseObserver.onError(t);
72+
}
73+
74+
@Override
75+
public void onCompleted() {
76+
logger.info("Client streaming complete");
77+
String reply = requestList.stream().collect(Collectors.joining(", "));
78+
EchoResponse response = EchoResponse.newBuilder().setMessage(reply).build();
79+
responseObserver.onNext(response);
80+
responseObserver.onCompleted();
81+
}
82+
};
83+
}
84+
85+
@Override
86+
public StreamObserver<EchoRequest> bidirectionalStreamingEcho(
87+
final StreamObserver<EchoResponse> responseObserver) {
88+
return new StreamObserver<EchoRequest>() {
89+
@Override
90+
public void onNext(EchoRequest request) {
91+
logger.info("Received bidirection streaming echo request: " + request.getMessage());
92+
EchoResponse response = EchoResponse.newBuilder().setMessage(request.getMessage()).build();
93+
responseObserver.onNext(response);
94+
}
95+
96+
@Override
97+
public void onError(Throwable t) {
98+
logger.log(Level.WARNING,
99+
"echo stream cancelled or had a problem and is no longer usable " + t.getMessage());
100+
}
101+
102+
@Override
103+
public void onCompleted() {
104+
logger.info("Bidirectional stream completed from client side");
105+
responseObserver.onCompleted();
106+
}
107+
};
108+
}
109+
}
110+
Lines changed: 109 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,109 @@
1+
/*
2+
* Copyright 2023 The gRPC Authors
3+
*
4+
* Licensed under the Apache License, Version 2.0 (the "License");
5+
* you may not use this file except in compliance with the License.
6+
* You may obtain a copy of the License at
7+
*
8+
* http://www.apache.org/licenses/LICENSE-2.0
9+
*
10+
* Unless required by applicable law or agreed to in writing, software
11+
* distributed under the License is distributed on an "AS IS" BASIS,
12+
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13+
* See the License for the specific language governing permissions and
14+
* limitations under the License.
15+
*/
16+
17+
package io.grpc.examples.multiplex;
18+
19+
import io.grpc.Grpc;
20+
import io.grpc.InsecureServerCredentials;
21+
import io.grpc.Server;
22+
import io.grpc.ServerBuilder;
23+
import io.grpc.StatusRuntimeException;
24+
import io.grpc.examples.helloworld.GreeterGrpc;
25+
import io.grpc.examples.helloworld.HelloReply;
26+
import io.grpc.examples.helloworld.HelloRequest;
27+
import io.grpc.examples.echo.EchoGrpc;
28+
import io.grpc.examples.echo.EchoRequest;
29+
import io.grpc.examples.echo.EchoResponse;
30+
import io.grpc.stub.StreamObserver;
31+
import java.io.IOException;
32+
import java.util.concurrent.TimeUnit;
33+
import java.util.logging.Logger;
34+
35+
/**
36+
* A sample gRPC server that serves both the Greeting and Echo services.
37+
*/
38+
public class MultiplexingServer {
39+
40+
private static final Logger logger = Logger.getLogger(MultiplexingServer.class.getName());
41+
42+
private final int port;
43+
private Server server;
44+
45+
public MultiplexingServer(int port) throws IOException {
46+
this.port = port;
47+
}
48+
49+
private void start() throws IOException {
50+
/* The port on which the server should run */
51+
server = Grpc.newServerBuilderForPort(port, InsecureServerCredentials.create())
52+
.addService(new MultiplexingServer.GreeterImpl())
53+
.addService(new EchoService())
54+
.build()
55+
.start();
56+
logger.info("Server started, listening on " + port);
57+
Runtime.getRuntime().addShutdownHook(new Thread() {
58+
@Override
59+
public void run() {
60+
// Use stderr here since the logger may have been reset by its JVM shutdown hook.
61+
System.err.println("*** shutting down gRPC server since JVM is shutting down");
62+
try {
63+
MultiplexingServer.this.stop();
64+
} catch (InterruptedException e) {
65+
e.printStackTrace(System.err);
66+
}
67+
System.err.println("*** server shut down");
68+
}
69+
});
70+
}
71+
72+
private void stop() throws InterruptedException {
73+
if (server != null) {
74+
server.shutdown().awaitTermination(30, TimeUnit.SECONDS);
75+
}
76+
}
77+
78+
/**
79+
* Await termination on the main thread since the grpc library uses daemon threads.
80+
*/
81+
private void blockUntilShutdown() throws InterruptedException {
82+
if (server != null) {
83+
server.awaitTermination();
84+
}
85+
}
86+
87+
/**
88+
* Main launches the server from the command line.
89+
*/
90+
public static void main(String[] args) throws IOException, InterruptedException {
91+
System.setProperty("java.util.logging.SimpleFormatter.format",
92+
"%1$tH:%1$tM:%1$tS %4$s %2$s: %5$s%6$s%n");
93+
94+
final MultiplexingServer server = new MultiplexingServer(50051);
95+
server.start();
96+
server.blockUntilShutdown();
97+
}
98+
99+
static class GreeterImpl extends GreeterGrpc.GreeterImplBase {
100+
101+
@Override
102+
public void sayHello(HelloRequest req, StreamObserver<HelloReply> responseObserver) {
103+
logger.info("Received sayHello request: " + req.getName());
104+
HelloReply reply = HelloReply.newBuilder().setMessage("Hello " + req.getName()).build();
105+
responseObserver.onNext(reply);
106+
responseObserver.onCompleted();
107+
}
108+
}
109+
}

0 commit comments

Comments
 (0)