Junior — Middle
Explain the concept of bidirectional streaming in gRPC.
sobes.tech AI
Answer from AI
Bidirectional streaming in gRPC allows the client and server to send and receive streams of messages simultaneously within a single connection.
This means that both parties can independently and concurrently transmit data, which is useful for interactive scenarios such as chat, streaming data updates, or real-time two-way communication.
In C#, this is implemented through asynchronous methods that return an AsyncDuplexStreamingCall<TRequest, TResponse> object. The client and server can read and write messages to the stream asynchronously.
Example of server-side implementation:
public override async Task Chat(
IAsyncStreamReader<ChatMessage> requestStream,
IServerStreamWriter<ChatMessage> responseStream,
ServerCallContext context)
{
await foreach (var message in requestStream.ReadAllAsync())
{
Console.WriteLine($"Received: {message.Text}");
await responseStream.WriteAsync(new ChatMessage { Text = "Echo: " + message.Text });
}
}
Here, the server reads messages from the client and immediately sends a response, maintaining a bidirectional data stream.