import io.grpc.Server; import io.grpc.ServerBuilder; import com.example.MyService; public class MyServer { public static void main(String[] args) { Server server = ServerBuilder.forPort(8080) .addService(new MyService()) .build() .start(); System.out.println("Server started on port 8080"); server.awaitTermination(); } } import io.grpc.Channel; import io.grpc.ClientCall; import io.grpc.ClientInterceptor; import io.grpc.ClientInterceptors; import io.grpc.Metadata; import io.grpc.MethodDescriptor; import io.grpc.Status; import io.grpc.protobuf.ByteString; import com.example.MyServiceGrpc; public class MyClient { private final Channel channel; public MyClient() { channel = Channel.forName("localhost:8080"); } public void sendMessage(String message) { MyServiceGrpc.MyServiceFuture future = channel.newCall(new MethodDescriptor(null, "sendMessage", ByteString.class, ByteString.class), new ClientInterceptor() { @Override public <ReqT, RespT> ClientCall<RespT> interceptCall(Channel channel, MethodDescriptor<ReqT, RespT> method, Metadata headers, CallOptions callOptions) { return channel.newCall(method, headers, callOptions); } }).start(); future.sendRequest(ByteString.copyFromUtf8(message)); FutureResponse response = future.get(); System.out.println("Received message: " + response.getMessage()); } public void close() { channel.shutdown(); } }


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