protobuf
syntax = "proto3";
package com.example.grpc;
service HelloWorldService {
rpc sayHello (HelloRequest) returns (HelloResponse);
}
message HelloRequest {
string name = 1;
}
message HelloResponse {
string message = 1;
}
shell
$ protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/helloworld.proto
package com.example.grpc;
import io.grpc.stub.StreamObserver;
public class HelloWorldServiceImpl extends HelloWorldServiceGrpc.HelloWorldServiceImplBase {
@Override
public void sayHello(HelloRequest request, StreamObserver<HelloResponse> responseObserver) {
String name = request.getName();
String message = "Hello, " + name;
HelloResponse response = HelloResponse.newBuilder()
.setMessage(message)
.build();
responseObserver.onNext(response);
responseObserver.onCompleted();
}
}
package com.example.grpc;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import java.io.IOException;
public class GrpcServer {
public static void main(String[] args) throws IOException, InterruptedException {
int port = 50051;
Server server = ServerBuilder.forPort(port)
.addService(new HelloWorldServiceImpl())
.build();
server.start();
System.out.println("Server started on port " + port);
server.awaitTermination();
}
}
package com.example.grpc;
import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
public class GrpcClient {
public static void main(String[] args) {
String host = "localhost";
int port = 50051;
ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port)
.usePlaintext()
.build();
HelloWorldServiceGrpc.HelloWorldServiceBlockingStub stub = HelloWorldServiceGrpc.newBlockingStub(channel);
HelloRequest request = HelloRequest.newBuilder()
.setName("World")
.build();
HelloResponse response = stub.sayHello(request);
System.out.println("Server response: " + response.getMessage());
channel.shutdown();
}
}