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

相关推荐
草莓熊Lotso14 小时前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
XR12345678815 小时前
汽车制造园区网络怎么建?柔性产线与 AGV 的选型逻辑
网络·汽车·制造
IT大白鼠1 天前
MSF二次开发与自定义模块编写
网络·安全·web安全·msf
Julien20041 天前
调查和解决 SELinux 问题
linux·运维·服务器·网络·学习方法
kekekzt1 天前
TCP协议的粘包问题介绍,IP分片,MTU,MSS,滑动窗口的概念及之间的关系
网络·网络协议·tcp/ip
mooooooooooye1 天前
2026 年跨平台 SSH 客户端怎么选?Xterminal、Termius、MobaXterm 谁更合适
服务器·网络·ssh
Blockchina1 天前
Codex 实战:从一句需求到可验收的 Linux 主机巡检脚本
运维·服务器·网络
江安下小雨1 天前
muduo网络库(十六):新增连接池模块
网络·c++
aiot189189352181 天前
机场候机大厅高空场景技术红线!蓝牙AOA不能做手机导航??!!
大数据·网络·人工智能·蓝牙aoa
从入门到退休1 天前
企业远程控制选型:向日葵SDK vs RustDesk自建,谁是更务实的选择?
运维·服务器·网络·远程工作·远程控制