例子来自FastRTPS文档。参考《FastRTPS User Manual.odt》
自定义Publisher:
class MyPublisher : public PublisherListener
{
Participant* mp_participant;
Publisher* mp_publisher;
MyPublisher(){
//Create participant(or receive it from somewhere else)
//Type “TestType” must be registered (can be done outside the class).
PublisherAttributes Wparam;
Wparam.topic.topicKind = NO_KEY; //Other possible value: WITH_KEY
Wparam.topic.topicDataType = "TestType";
Wparam.topic.topicName = "Test_topic";
//Modify the rest of the parameters as you wish
mp_publisher = Domain::createPublisher(mp_participant,Wparam,this);
if(mp_publisher == nullptr)
cout << "Publisher creation failed" << endl;
}
~MyPublisher(){ Domain::removePublisher(mp_publisher);}
void onPublicationMatched(Publisher* pub,MatchingInfo info) {
if(info.status == MATCHED_MATCHING)
cout << “Publication Matched” << endl;
}
void run(){
if(mp_publisher!=nullptr){
TestType obj;
//Fill the structure
mp_publisher->write(&obj);
}
}
};
自定义Subscriber:
class MySubscriber : public SubscriberListener
{
Participant* mp_participant;
Subscriber* mp_subscriber;
MySubscriber(){
//Create participant;
//Type “TestType” must be registered (can be done outside the class).
SubscriberAttributes Rparam;
Rparam.topic.topicKind = NO_KEY; //Other possible value: NO_KEY
Rparam.topic.topicDataType = "TestType";
Rparam.topic.topicName = "Test_topic";
//Modify the rest of the parameters as you wish
mp_subscriber = Domain::createSubscriber(mp_participant,Rparam,this);
if(mp_subscriber == nullptr)
cout << "Subscriber creation failed" << endl;
}
~MySubscriber { Domain::removeSubscriber(mp_subscriber) }
void onSubscriptionMatched(Subscriber* sub,MatchingInfo info) {
if(info.status == MATCHED_MATCHING)
cout << “Subscriber Matched” << endl;
}
void onNewDataMessage(Subscriber* sub){
TestType obj;
SampleInfo_t info;
if(mp_subscriber->takeNextData(&obj,&info)) {
if(info.sampleKind == ALIVE){
//print the data object fields
}
}
}
//If you read or take the data in the onNewDataMessage callback you should
//avoid using waitForNewMessage() in you main loop because it would never exit.
void run(){
cout << "Enter number to exit: " << endl;
int aux;
cin >> aux;
}
};