diff --git a/.gitignore b/.gitignore index b3db397..2a03973 100644 --- a/.gitignore +++ b/.gitignore @@ -36,3 +36,6 @@ build/ # Todo file TODO.md +# Eclipse +.cproject +.project diff --git a/CMakeLists.txt b/CMakeLists.txt index ebdbbec..6b081b6 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -142,6 +142,9 @@ if (examples) add_executable(binary_data examples/binary_data.cpp) target_link_libraries(binary_data redox) + add_executable(binary_data_publish examples/binary_data_publish.cpp) + target_link_libraries(binary_data_publish redox) + add_executable(pub_sub examples/pub_sub.cpp) target_link_libraries(pub_sub redox) diff --git a/examples/binary_data_publish.cpp b/examples/binary_data_publish.cpp new file mode 100644 index 0000000..f9c6a41 --- /dev/null +++ b/examples/binary_data_publish.cpp @@ -0,0 +1,51 @@ +/** +* Basic use of Redox to publish and subscribe binary data. +*/ + +#include +#include +#include +#include +#include "redox.hpp" + +using namespace std; +using redox::Redox; +using redox::Command; + +/** +* Random string generator. +*/ +std::string random_string(size_t length) { + std::string str(length, 0); + std::generate_n(str.begin(), length, []{ return (unsigned char)rand(); }); + return str; +} + +int main(int argc, char* argv[]) { + + redox::Redox rdx; // Initialize Redox + redox::Subscriber sub; // Initialize Subscriber + + if(!rdx.connect("localhost", 6379)) return 1; + if(!sub.connect("localhost", 6379)) return 1; + + string binary_key = random_string(100); + string binary_data = random_string(10000); + + cout << "binary data size " << binary_data.length() << endl; + + sub.subscribe("test", [binary_data](const string& topic, const string& msg) { + cout << "msg data size " << msg.length() << endl; + if(msg == binary_data) cout << "Binary data matches!" << endl; + }); + + this_thread::sleep_for( chrono::milliseconds(1000) ); + + rdx.publish("test", binary_data); + + this_thread::sleep_for( chrono::milliseconds(1000) ); + + rdx.disconnect(); + sub.disconnect(); + return 0; +} diff --git a/src/subscriber.cpp b/src/subscriber.cpp index 47815d6..8847357 100644 --- a/src/subscriber.cpp +++ b/src/subscriber.cpp @@ -152,15 +152,17 @@ void Subscriber::subscribeBase(const string cmd_name, const string topic, // Message for subscribe else if ((reply->type == REDIS_REPLY_ARRAY) && (reply->elements == 3)) { char *msg = reply->element[2]->str; + int len = reply->element[2]->len; if (msg && msg_callback) - msg_callback(topic, reply->element[2]->str); + msg_callback(topic, string(msg, len)); } // Message for psubscribe else if ((reply->type == REDIS_REPLY_ARRAY) && (reply->elements == 4)) { - char *msg = reply->element[2]->str; + char *msg = reply->element[3]->str; + int len = reply->element[3]->len; if (msg && msg_callback) - msg_callback(reply->element[2]->str, reply->element[3]->str); + msg_callback(reply->element[2]->str, string(msg, len)); } else