पाठ 11 / 25

Client Streaming

Upload many messages, get one answer.

Aggregation on the server

In client streaming, the client sends a sequence of messages and the server replies once, typically after processing them all: uploading batches of records, sending sensor readings, or streaming chunks of a file. The server reads the request iterator and returns a summary. Validate each message as it arrives and decide whether a bad item rejects the whole call or is reported in the response.

Uploading items as a stream

Python sketch.

# server: consume the iterator, return one response
def UploadItems(self, request_iterator, context):
    accepted = 0
    for item in request_iterator:
        if item.quantity <= 0:
            context.abort(grpc.StatusCode.INVALID_ARGUMENT, "quantity must be positive")
        save(item)
        accepted += 1
    return order_pb2.UploadItemsResponse(accepted=accepted)

# client: pass a generator of messages
def items():
    for row in csv_rows:
        yield order_pb2.OrderItem(product_id=row["sku"], quantity=int(row["qty"]))

response = stub.UploadItems(items(), timeout=60)

Mind message size limits

gRPC limits message size (4 MB by default for receiving in many implementations); stream chunks instead of sending one huge message.

त्वरित जाँच: When does a client-streaming RPC typically return its response?

  • Never
  • Before the first message
  • Once per client message
  • After the server has read the client's stream
Answer

After the server has read the client's stream — One response at the end.