Implement pub/sub support for protobuf side.

This commit is contained in:
Christoph Heiss 2018-03-04 22:26:42 +01:00
parent 7955e22780
commit 6c2cc7b444
2 changed files with 38 additions and 0 deletions

View file

@ -11,6 +11,7 @@
#include <vector>
#include <ostream>
#include <arpa/inet.h>
#include <functional>
#include "asio.hpp"
#include "clipp.h"
@ -136,6 +137,16 @@ public:
return command;
}
void listen_for_messages(std::function<void(const std::string&, const std::string&)> callback)
{
for (;;) {
rslp::Command command;
command.ParseFromString(receive_data());
callback(command.data(1).str(), command.data(2).str());
}
}
private:
std::string receive_data()
{
@ -209,6 +220,15 @@ int main(int argc, char* argv[])
rslp::Command result{client.send_command(command)};
std::cout << result << std::endl;
if (result.data_size() > 0) {
auto data{result.data(0)};
if (data.data_case() == rslp::Command_Data::DataCase::kStr &&
(data.str() == "subscribe" || data.str() == "psubscribe")) {
client.listen_for_messages([](const auto& channel, const auto& message) {
std::cout << channel << ": " << message << std::endl;
});
}
}
}
client.close();

View file

@ -197,10 +197,28 @@ public:
resply_result_to_rslp(response, result);
send_data(response);
if (result.type == resply::Result::Type::Array &&
result.array[0].type == resply::Result::Type::String &&
(result.array[0].string == "subscribe" || result.array[0].string == "psubscribe")) {
listen_for_messages();
}
}
}
private:
void listen_for_messages()
{
client_.listen_for_messages([this](const auto& channel, const auto& message) {
rslp::Command response;
response.add_data()->set_str("message");
response.add_data()->set_str(channel);
response.add_data()->set_str(message);
send_data(response);
});
}
std::string receive_data()
{
asio::error_code error_code;