gRPC: How can I distinguish bi-streaming clients at server side?

前端 未结 1 457
刺人心
刺人心 2021-01-28 08:54

In this tutorial and example code, a server can call onNext() method on every stream observer, which will broadcast messages to all clients bi-streaming wi

相关标签:
1条回答
  • 2021-01-28 09:40

    The answer depends a bit on how the clients will be identified. If the initial request provided a handle (like a username, but not registered ahead-of-time), then you could just wait for the first onNext():

      public StreamObserver<Chat.ChatMessage> chat(StreamObserver<Chat.ChatMessageFromServer> responseObserver) {
        return new StreamObserver<Chat.ChatMessage>() {
          @Override
          public void onNext(Chat.ChatMessage value) {
            String userHandle = value.getHandle();
            // observers would now be a map, not a set
            observers.put(userHandle, responseObserver);
            ...
    

    Let's say instead that all users are logged in, and provide a token in the headers, like OAuth. Then you would use an interceptor to authenticate the user and Context to propagate it to the application, as in https://stackoverflow.com/a/40113309/4690866 .

      public StreamObserver<Chat.ChatMessage> chat(StreamObserver<Chat.ChatMessageFromServer> responseObserver) {
        // USER_IDENTITY is a Context.Key, also used by the interceptor
        User user = USER_IDENTITY.get();
        observers.put(user.getName(), responseObserver);
        return new StreamObserver<Chat.ChatMessage>() {
            ...
    

    The first one is easier/nicer when the identification only applies to this one RPC. The second one is easier/nicer when the identification applies to many RPCs.

    0 讨论(0)
提交回复
热议问题