2
votes

My scenario is,

Server and client initiated

server sends message to client ,(server initiating the message exchange)

client receives the message and reply back with the response

If so, Please help me with grpc-java sample code.

All I could find is client sending the message to the server, for that server sends back the response.

1
I think grpc does not support truly server-initiated calls to the client at the RPC layer. You could implement this at the application layer by using bidirectional streaming of Messages, as in user675693's answer. - Adam Bliss

1 Answers

0
votes

Server sending message first can be achieved by Bidirectional-streaming

https://grpc.io/docs/reference/java/generated-code.html

// Client Side:
volatile StreamObserver<Message> requestOb;

StreamObserver<Message> responseOb = new StreamObserver<>() {
  @Override public void onNext(Message msg) { requestOb.onNext(msg); }
  @Override public void onError(Throwable t) { requestOb.onError(t); }
  @Override public void onCompleted() { requestOb.onCompleted(); }
}
requestOb = stub.echoTheServer(responseOb);

// Server side:
@Override
public StreamObserver<Message> echoTheServer(StreamObserver<Message> responseOb) {
  for (int i = 0; i < 100; i++) {
    responseOb.onNext(new Message());
  }
  responseOb.onComplete();
  return new StreamObserver<Message>() {
    @Override public void onNext(Message msg) {}
    @Override public void onError(Throwable t) { responseOb.onError(t); }
    @Override public void onCompleted() {}
  }
}