Sample 9. channel using regex name matching
This sample modifies chat_direct sample to show how we can pass
messages and events among distributed processes based on regex name
matching.
Lets walk thru the code.
All name space related types are defined in chat_defs.hpp.
First we set regex_id to be the id_type. With regex_id, applications
can use strings and regex patterns (Boost.Regex) as message ids and
names (also we need to include <boost/regex.hpp>).
Next we instantiate the channel type. A associative name space is
implemented as a linear namespace with associative lookup. The
lookup method is defined as the last template argument of
linear_name_space class template. The default value "true" means "exact
matching"; for "associative lookup" we set it to false.
typedef regex_id
id_type;
typedef
channel<
id_type,
boost_platform,
mt_synch<boost_platform>,
abstract_executor, //force in place execution
linear_name_space<id_type, abstract_executor,
mt_synch<boost_platform>, false> ///false - assoc matching
>
chat_chan;
Next we define ids/names we are going to use in this channel
application. We define 2 sets of ids: plain text strings and
regex patterns:
id_type basketball
= "[sports]: basketball";
id_type tennis
= "[sports]: tennis";
id_type
baseball = "[sports]: baseball";
id_type
all_balls(new boost::regex(".*ball.*"));
id_type tax =
"[financial]: tax";
id_type stock
= "[financial]: stock";
id_type
investment = "[financial]: investment";
id_type
all_financial(new boost::regex(".*financial.*"));
Next we define a simple structure for message data:
struct chat_msg {
string
source_;
string
data_;
chat_msg(char *s, char *d) : source_(s), data_(d) {}
chat_msg() {} //have to define this for marshaling to work
//serialization function for chat_msg
template <typename Archive>
void
serialize(Archive & ar, const unsigned int version)
{
ar &source_ & data_;
}
};
The code in the peer process (chat1.cpp,
chat2.cpp) are similar to
other samples. We bind to names to send messages to distributed
processes, except that
we are using regex matching for name-matching. So if application
subscribe to "all_balls",
it will receive messages for both
"basketball", "baseball" and any other balls.
Complete source code listing:
chat_defs.hpp
chat1.cpp
chat2.cpp