简体   繁体   English

如何在 C++ 中向 grpc 完成队列添加事件?

[英]How to add an event to grpc completion queue in C++?

I am trying to implement an async GRPC server, where whenever the client makes a call it gets an indefinite stream of messages.我正在尝试实现一个异步 GRPC 服务器,每当客户端进行调用时,它都会收到不确定的消息流。 I read through the official documentation.我通读了官方文档。 It doesn't cover the scenario where I want to keep the stream open for each RPC.它不包括我希望为每个 RPC 保持流打开的场景。 This article - https://www.gresearch.co.uk/article/lessons-learnt-from-writing-asynchronous-streaming-grpc-services-in-c/ addresses the issue of keeping the stream open by basically putting the callback handler object in the completion queue again.这篇文章 - https://www.gresearch.co.uk/article/lessons-learnt-from-writing-asynchronous-streaming-grpc-services-in-c/通过基本上放置回调来解决保持流打开的问题处理程序对象再次出现在完成队列中。

The article suggests:文章建议:

if (HasData())
{
    responder_.Write(reply_, this);
}
else
{
    grpc::Alarm alarm;
    alarm.Set(completion_queue_, gpr_now(gpr_clock_type::GPR_CLOCK_REALTIME), this);
}

I tried using the Alarm object approach as suggested in this article but for some reason on the next Next function call on completion queue I get ok argument as false - GPR_ASSERT(cq_->Next(&tag, &ok));我尝试使用本文中建议的警报对象方法,但出于某种原因,在完成队列上的下一个Next函数调用中,我将ok参数设为 false - GPR_ASSERT(cq_->Next(&tag, &ok)); . . As a result, I have to close the server and am unable to wait on a stream till further data is available.结果,我必须关闭服务器并且无法等待流,直到有更多数据可用。

I am able to receive data fine till the else case is not hit.我能够很好地接收数据,直到没有遇到else情况。

Could someone please help me identify what I might be doing wrong?有人可以帮我确定我可能做错了什么吗? I am unable to find much C++ resources on GRPC.我无法在 GRPC 上找到很多 C++ 资源。 Thanks!谢谢!

  1. When Alarm goes out of scope, it will generate a Cancel() causing you to get !ok in Next().当 Alarm 超出范围时,它会生成一个 Cancel() 使您在 Next() 中获得 !ok。

  2. if you want to use this, you would need to put the Alarm into your class scope and trigger it:如果您想使用它,您需要将 Alarm 放入您的类范围并触发它:

    std::unique_ptr<Alarm> alarm_;
    alarm_.reset(new Alarm);
    alarm_->Set(cq_, grpc_timeout_seconds_to_deadline(10), this);

from the doc on Alarm::Set:来自 Alarm::Set 上的文档:

Trigger an alarm instance on completion queue cq at the specified time.在指定时间在完成队列 cq 上触发警报实例。

Once the alarm expires (at deadline) or it's cancelled (see Cancel), an event with tag tag will be added to cq.一旦警报到期(在截止日期)或被取消(请参阅取消),一个带有 tag 标签的事件将被添加到 cq。 If the alarm expired, the event's success bit will be true, false otherwise (ie, upon cancellation).如果警报过期,则事件的成功位将为真,否则为假(即取消时)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM