add push notification example.

This commit is contained in:
qicosmos
2019-05-23 19:58:17 +08:00
parent fef215e7e6
commit e61c3d51c6
2 changed files with 77 additions and 0 deletions
+54
View File
@@ -85,6 +85,57 @@ std::string echo(rpc_conn conn, const std::string& src) {
return src;
}
struct notifier {
public:
notifier() {
std::thread thd([this] {
while (!stop_) {
if (has_subs_) {
notify("this a notification from the server");
}
std::this_thread::sleep_for(std::chrono::seconds(1));
}
});
thd.detach();
}
~notifier() {
stop_ = true;
}
void sub(rpc_conn conn) {
if (!has_subs_) {
has_subs_ = true;
}
auto req_id = conn.lock()->request_id();
std::unique_lock<std::mutex> lock(mtx_);
subs_.emplace_back(conn, req_id);
}
private:
void notify(const std::string& result) {
{
std::unique_lock<std::mutex> lock(mtx_);
for (auto& pair : subs_) {
auto sp_conn = pair.first.lock();
if (sp_conn) {
sp_conn->pack_and_response(pair.second, result);
}
}
subs_.clear();
}
has_subs_ = false;
}
std::vector<std::pair<rpc_conn, uint64_t>> subs_;
std::mutex mtx_;
std::atomic_bool has_subs_ = { false };
bool stop_ = false;
};
int main() {
rpc_server server(9000, std::thread::hardware_concurrency());
@@ -100,6 +151,9 @@ int main() {
server.register_handler<ExecMode::async>("async_echo", async_echo);
server.register_handler("echo", echo);
notifier n;
server.register_handler<ExecMode::async>("sub", &notifier::sub, &n);
server.run();
std::string str;