从官方gRPC c ++示例中:https://github.com/grpc/grpc/tree/v1.33.1/examples/cpp/route_guide
route_guide_server.cc:
...
Status RouteChat(ServerContext* context,
ServerReaderWriter<RouteNote, RouteNote>* stream) override {
RouteNote note;
while (stream->Read(¬e)) {
std::unique_lock<std::mutex> lock(mu_);
for (const RouteNote& n : received_notes_) {
if (n.location().latitude() == note.location().latitude() &&
n.location().longitude() == note.location().longitude()) {
stream->Write(n);
}
}
received_notes_.push_back(note);
}
return Status::OK;
}
...
服务器使用while循环从流中读取。那么,如果流仍处于打开状态,并且服务器正在等待来自客户端的消息,由于我的服务器旨在同时与多个客户端通信,那么它将切换为处理来自其他客户端的请求吗?
如果没有,有什么更好的方法让服务器等待流中的消息,同时又可以在等待过程中与其他客户端进行交互?
答案 0 :(得分:0)
在这种情况下,您可以使用异步 gRPC 服务器。 doc
https://github.com/grpc/grpc/blob/master/test/cpp/qps/server_async.cc 可能是了解如何使用它的示例,但请记住,这并不容易理解。