0Pricing
gRPC & High Performance APIs · 课时

双向流式传输

掌握双向流式传输,使客户端和服务器能够同时发送一系列消息

双向流式传输 是 CoddyKit 上的免费 gRPC & High Performance APIs 课时。 这是第 3 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 gRPC & High Performance APIs 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 gRPC & High Performance APIs 课程共包含 4 节课。

本课时的部分内容尚未翻译,以英文显示。

Bidirectional Streaming: Two-Way Talk

What if both sides in a conversation could speak and listen at the same time? That's bidirectional streaming in gRPC! It allows both the client and server to send a sequence of messages to each other, concurrently.

Why Use Bidi Streaming?

Bidirectional streaming is perfect for applications needing real-time, interactive communication. Think of it like a phone call where both parties can talk and hear simultaneously.

  • Chat applications: Users send and receive messages instantly.
  • Live updates: Servers push data to clients as events happen.
  • Gaming: Synchronized game state updates between players and server.

Defining a Bidi Stream Service

To enable bidirectional streaming, you use the stream keyword for both the request and response types in your .proto file.

This tells gRPC that the method will handle a continuous flow of messages in both directions.

syntax = "proto3";

package chat;

message ChatMessage {
  string user = 1;
  string message = 2;
}

service ChatService {
  rpc Chat(stream ChatMessage) returns (stream ChatMessage);
}

Server: Receiving Client Messages

On the server, your service method will receive a StreamObserver for the incoming client messages. You'll implement its methods to process each message.

  • onNext(msg): Called for each message from the client.
  • onError(t): Called if the client stream encounters an error.
  • onCompleted(): Called when the client finishes sending messages.

Server: Sending Back Responses

The server also gets a StreamObserver (usually named responseObserver) to send messages back to the client. This allows the server to push multiple responses.

  • responseObserver.onNext(resp): Sends a message to the client.
  • responseObserver.onError(t): Signals an error to the client.
  • responseObserver.onCompleted(): Closes the server's outgoing stream.

Client: Starting the Conversation

On the client, you'll use an asynchronous (non-blocking) stub to call the streaming method. This call immediately returns a StreamObserver.

This returned observer is what the client uses to send messages to the server.

Client: Two-Way Communication

The client needs two main parts for bidirectional streaming:

  1. An observer for outgoing messages: This is used to onNext() messages to the server.
  2. An observer for incoming messages: This is passed to the gRPC call to handle responses from the server.

Both streams operate independently and concurrently.

Full Server Bidi Stream Example

Here's a simplified gRPC server that echoes messages received from the client. Remember to compile your .proto file and include gRPC dependencies.

Try running this example:

import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

// Assuming ChatServiceGrpc and ChatMessage are generated
// from the proto definition.
import chat.ChatServiceGrpc;
import chat.ChatMessage;

public class ChatServer {

  public static void main(String[] args) throws Exception {
    Server server = ServerBuilder.forPort(50051)
        .addService(new ChatServiceImpl())
        .build();

    server.start();
    System.out.println("Server started on port 50051");
    server.awaitTermination();
  }

  static class ChatServiceImpl extends ChatServiceGrpc.ChatServiceImplBase {
    @Override
    public StreamObserver<ChatMessage> chat(
        final StreamObserver<ChatMessage> responseObserver) {

      return new StreamObserver<ChatMessage>() {
        @Override
        public void onNext(ChatMessage request) {
          // Received a message from the client
          System.out.println("Server received: " + request.getMessage());
          // Echo it back to the client
          ChatMessage response = ChatMessage.newBuilder()
              .setUser("Server")
              .setMessage("Echo: " + request.getMessage())
              .build();
          responseObserver.onNext(response);
        }

        @Override
        public void onError(Throwable t) {
          System.err.println("Server error: " + t.getMessage());
        }

        @Override
        public void onCompleted() {
          System.out.println("Client stream completed.");
          responseObserver.onCompleted(); // Close server stream
        }
      };
    }
  }
}

Full Client Bidi Stream Example

This client sends a few messages and listens for responses. Run the server first, then this client. The client will send messages and print the server's echoes.

Try running this example:

import io.grpc.ManagedChannel;
import io.grpc.ManagedChannelBuilder;
import io.grpc.stub.StreamObserver;

// Assuming ChatServiceGrpc and ChatMessage are generated
// from the proto definition.
import chat.ChatServiceGrpc;
import chat.ChatMessage;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ChatClient {

  public static void main(String[] args) throws Exception {
    ManagedChannel channel = ManagedChannelBuilder.forAddress("localhost", 50051)
        .usePlaintext() // For demonstration, use TLS in production
        .build();

    ChatServiceGrpc.ChatStub asyncStub = ChatServiceGrpc.newStub(channel);

    CountDownLatch finishLatch = new CountDownLatch(1);

    StreamObserver<ChatMessage> requestObserver = asyncStub.chat(
        new StreamObserver<ChatMessage>() {
          @Override
          public void onNext(ChatMessage response) {
            System.out.println("Client received: " + response.getMessage());
          }

          @Override
          public void onError(Throwable t) {
            System.err.println("Client error: " + t.getMessage());
            finishLatch.countDown();
          }

          @Override
          public void onCompleted() {
            System.out.println("Server stream completed.");
            finishLatch.countDown();
          }
        });

    try {
      // Client sends messages
      for (int i = 0; i < 3; i++) {
        ChatMessage request = ChatMessage.newBuilder()
            .setUser("Client")
            .setMessage("Hello " + i)
            .build();
        requestObserver.onNext(request);
        Thread.sleep(500); // Simulate delay
      }
    } catch (RuntimeException | InterruptedException e) {
      requestObserver.onError(e);
      throw e;
    } finally {
      requestObserver.onCompleted(); // Client finishes sending
    }

    if (!finishLatch.await(1, TimeUnit.MINUTES)) {
      System.err.println("Client timed out waiting for server response.");
    }
    channel.shutdownNow().awaitTermination(5, TimeUnit.SECONDS);
  }
}

Bidirectional Stream Check

You've learned about bidirectional streaming. Which statement best describes how both client and server communicate in a gRPC bidirectional stream?

Bidirectional Streaming Recap

Great job! You've mastered bidirectional streaming in gRPC.

  • It enables both client and server to send sequences of messages.
  • Ideal for real-time, interactive applications like chat.
  • Defined using the stream keyword for both request and response in Protobuf.
  • Requires separate logic on both client and server to manage incoming and outgoing message streams.

This powerful pattern opens up many possibilities for highly responsive distributed systems.

常见问题解答

「双向流式传输」课时是免费的吗?

是的 — 「双向流式传输」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 gRPC & High Performance APIs 课程的其余内容,请升级到 CoddyKit PRO。 gRPC & High Performance APIs 课程共包含 4 节课。

「双向流式传输」这节课中我会学到什么?

掌握双向流式传输,使客户端和服务器能够同时发送一系列消息 你通过在浏览器中直接运行的动手代码来练习 gRPC & High Performance APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。

学习 gRPC & High Performance APIs 需要有经验吗?

无需任何先前经验。CoddyKit 上的 gRPC & High Performance APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 3 节课,共 4 节。

「双向流式传输」课时需要多长时间?

大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。

我能在这节 gRPC & High Performance APIs 课中编写并运行代码吗?

能。每节 gRPC & High Performance APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。

此课程中的所有课时

  1. 服务器流式传输详解
  2. 客户端流式传输详解
  3. 双向流式传输
  4. 流式控制与背压
← 返回 gRPC & High Performance APIs