syntax = "proto3"; service HelloService { rpc sayHello(HelloMessage) returns (HelloResponse); } message HelloMessage { string name = 1; } message HelloResponse { string message = 1; } public class HelloServiceImpl extends HelloServiceGrpc.HelloServiceImplBase { @Override public void sayHello(HelloMessage request, StreamObserver<HelloResponse> responseObserver) { String name = request.getName(); String message = "Hello, " + name + "!"; HelloResponse response = HelloResponse.newBuilder() .setMessage(message) .build(); responseObserver.onNext(response); responseObserver.onCompleted(); } } public class Server { public static void main(String[] args) throws IOException, InterruptedException { int port = 50051; Server server = ServerBuilder.forPort(port) .addService(new HelloServiceImpl()) .build() .start(); System.out.println("Server started on port " + port); server.awaitTermination(); } } public class Client { public static void main(String[] args) { String host = "localhost"; int port = 50051; ManagedChannel channel = ManagedChannelBuilder.forAddress(host, port) .usePlaintext() .build(); HelloServiceGrpc.HelloServiceBlockingStub stub = HelloServiceGrpc.newBlockingStub(channel); HelloMessage request = HelloMessage.newBuilder() .setName("John") .build(); HelloResponse response = stub.sayHello(request); System.out.println(response.getMessage()); channel.shutdown(); } }


上一篇:
下一篇:
切换中文