protobuf syntax = "proto3"; package com.example.grpc; service Greeter { rpc SayHello (HelloRequest) returns (HelloReply) {} } message HelloRequest { string name = 1; } message HelloReply { string message = 1; } import io.grpc.Server; import io.grpc.ServerBuilder; import io.grpc.stub.StreamObserver; public class GreeterServer { public static void main(String[] args) throws Exception { Server server = ServerBuilder.forPort(50051) .addService(new GreeterImpl()) .build() .start(); System.out.println("Server started"); server.awaitTermination(); } static class GreeterImpl extends GreeterGrpc.GreeterImplBase { @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { String message = "Hello, " + request.getName(); HelloReply reply = HelloReply.newBuilder().setMessage(message).build(); responseObserver.onNext(reply); responseObserver.onCompleted(); } } } import io.grpc.ManagedChannel; import io.grpc.ManagedChannelBuilder; public class GreeterClient { public static void main(String[] args) { ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051).usePlaintext().build(); GreeterGrpc.GreeterBlockingStub stub = GreeterGrpc.newBlockingStub(channel); HelloRequest request = HelloRequest.newBuilder().setName("John").build(); HelloReply reply = stub.sayHello(request); System.out.println("Server replied: " + reply.getMessage()); channel.shutdown(); } } StreamObserver<HelloReply> responseObserver = new StreamObserver<HelloReply>() { @Override public void onNext(HelloReply reply) { } @Override public void onError(Throwable t) { System.out.println("Error occurred: " + t.getMessage()); } @Override public void onCompleted() { } }; @Override public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) { try { // ... responseObserver.onNext(reply); responseObserver.onCompleted(); } catch (Exception e) { responseObserver.onError(e); } } Server server = ServerBuilder.forPort(50051) .build() .start(); ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051) .usePlaintext() .build();


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