12
votes

Is it possible to only stream to certain clients from a gRPC server?

I believe what I'm looking for is something like Pusher, where you have a channel for a client and you can publish messages that can be seen only by a client that has access to that channel.

What I'm struggling with is understanding what are the steps we need to take to do something like this.

Thinking about web-sockets I believe we can store each client connection, then we can find that connection and send messages. How can we do a similar thing with gRPC?

1

1 Answers

7
votes

As per as i understood the question. You want to send the the message to the particular client in gRPC. This is very much possible using Server side streaming or Bi-directional streaming in gRPC.

For example:

Define a server side streaming or bidi streaming api

rpc ListFeatures(Rectangle) returns (stream Feature) {}

On Server side:

func ListFeatures(rect *pb.Rectangle, stream pb.RouteGuide_ListFeaturesServer) error {
  // Save this stream instance in the server on a map or other suitable data structure
  // so that you can query for this stream instance later
  // This will act same like your websocket session
}

When you want to send something to a specific client then get the stream instance and do

err := stream.Send(feature); // Any times as required

On the client, it will be waiting for messages like this

stream, err := client.ListFeatures(ctx, rect)

for {
    feature, err := stream.Recv()
    ...
    // handle message here
}

Same thing can be done for bidi streaming rpc also. I hope this answers your question