gRPC 四模式之 服务器端流RPC模式

服务器端流RPC模式

在一元 RPC 模式中,gRPC 服务器端和 gRPC 客户端在通信时始终只有一个请求和一个响应。在服务器端流 RPC 模式中,服务器端在接收到客户端的请求消息后,会发回一个响应的序列。这种多个响应所组成的序列也被称为"流"。在将所有的服务器端响应发送完毕之后,服务器端会以 trailer 元数据的形式将其状态发送给客户端,从而标记流的结束。

c++ 实现服务器端主动推送消息

在gRPC中,服务端主动向客户端发送数据通常是通过服务器端流式RPC实现的。在这种模式下,客户端发送一个请求到服务器,获取一个读取服务端流的响应。这种模式可以让服务器主动推送消息给客户端。

以下是一个C++的例子,展示了一个简单的服务器端流式RPC的实现:

cpp 复制代码
// .proto file
service MyService {
  rpc MyStreamingMethod(MyRequest) returns (stream MyResponse);
}

// Server implementation
class MyServiceImpl final : public MyService::Service {
  Status MyStreamingMethod(const MyRequest* request, ServerWriter<MyResponse>* writer) override {
    MyResponse response;
    for (int i = 0; i < 10; ++i) {
      response.set_data("Data " + std::to_string(i));
      writer->Write(response);
    }
    return Status::OK;
  }
};

// Client implementation
void MyClient::MyStreamingMethod() {
  MyRequest request;
  request.set_data("Hello");

  ClientContext context;
  std::unique_ptr<ClientReader<MyResponse>> reader(
      stub_->MyStreamingMethod(&context, request));

  MyResponse response;
  while (reader->Read(&response)) {
    // Process response.
    std::cout << response.data() << std::endl;
  }

  Status status = reader->Finish();
  if (status.ok()) {
    std::cout << "MyStreamingMethod succeeded." << std::endl;
  } else {
    std::cout << "MyStreamingMethod failed." << std::endl;
  }
}

在这个例子中,MyStreamingMethod是一个服务器端流式RPC,客户端发送一个MyRequest请求,然后读取一个流的MyResponse响应。服务器在接收到请求后,通过ServerWriter对象向客户端发送多个响应。

客户端向服务端发送请求后的回复,通常是通过返回一个Status对象来实现的。在上述例子中,MyStreamingMethod在完成所有响应发送后,返回一个Status::OK表示成功。客户端通过调用ClientReader::Finish方法来获取这个状态。


分享一个有趣的 学习链接:https://xxetb.xet.tech/s/HY8za

相关推荐
YuMiao17 小时前
gstatic连接问题导致Google Gemini / Studio页面乱码或图标缺失问题
服务器·网络协议
Jony_3 天前
高可用移动网络连接
网络协议
chilix4 天前
Linux 跨网段路由转发配置
网络协议
DianSan_ERP5 天前
电商API接口全链路监控:构建坚不可摧的线上运维防线
大数据·运维·网络·人工智能·git·servlet
呉師傅5 天前
火狐浏览器报错配置文件缺失如何解决#操作技巧#
运维·网络·windows·电脑
gihigo19985 天前
基于TCP协议实现视频采集与通信
网络协议·tcp/ip·音视频
2501_946205525 天前
晶圆机器人双臂怎么选型?适配2-12寸晶圆的末端效应器有哪些?
服务器·网络·机器人
linux kernel5 天前
第七部分:高级IO
服务器·网络
数字护盾(和中)5 天前
BAS+ATT&CK:企业主动防御的黄金组合
服务器·网络·数据库
~远在太平洋~5 天前
Debian系统如何删除多余的kernel
linux·网络·debian