mirror of
https://github.com/qicosmos/rest_rpc.git
synced 2026-08-30 09:00:48 +08:00
add push notification example.
This commit is contained in:
@@ -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", ¬ifier::sub, &n);
|
||||
|
||||
server.run();
|
||||
|
||||
std::string str;
|
||||
|
||||
Reference in New Issue
Block a user