Search code examples
javastreaminggrpc-java

Bidirectional streaming java client


I am working on creating a java library for a bidirectional streaming on SSL sockets (cannot re-use gRPC/HTTP2 streaming clients).

My initial thought is to create 3 components:

  1. StreamingConnection.
  2. StreamReader (observe on input stream).
  3. StreamWriter (writes to output stream).
  4. StreamingClient

Callers interact with StreamingClient which calls StreamingConnection.connect() to create a socket connection and passes the input stream as constructor argument to StreamReader and outputStream too StreamWriter.

But it turns out Reader will need to write messages on output stream based on incoming messages. Also, it might happen that based server can send new host details which client should connect to, in this case we do the cleaning and begin streaming again.

I am trying to visualise what is the best way to communicate between these components? Passing events, mediator or any other pattern that I should explore?

Any insights or class dia of gRPC bidirectional streams?


Solution

  • I don't think you need to implement your own StreamWriter (that's what an async stub returns you when you invoke the streaming RPC on it), unless you want to wrap it with another layer of logic. Most of the time, implementations encapsulate all StreamingConnection, StreamReader and StreamWriter within the StreamingClient class. Each of them are not complex in terms of implementation (StreamingConnection builds a channel and create a stub, which is used for making RPC calls; StreamReader is the response handler that implements StreamObserver; StreamWriter is what gRPC library provides you for sending messages to the server). Putting them within the same class (as inner classes or even anonymous classes) allows them to interact with each other.