Trivial applications

Note

To successfully run the following examples, please make sure that NFD is properly configured and running. For more information about NFD, refer to NFD’s official homepage.

Trivial consumer

In the following trivial example, a consumer creates a Face with default transport (UnixTransport) and sends an Interest for /localhost/testApp/randomData. While expressing Interest, the app specifies three callbacks to be called when Data/Nack is retrieved or Interest times out.

  1/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
  2/*
  3 * Copyright (c) 2013-2021 Regents of the University of California.
  4 *
  5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  6 *
  7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
  8 * terms of the GNU Lesser General Public License as published by the Free Software
  9 * Foundation, either version 3 of the License, or (at your option) any later version.
 10 *
 11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 13 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 14 *
 15 * You should have received copies of the GNU General Public License and GNU Lesser
 16 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 17 * <http://www.gnu.org/licenses/>.
 18 *
 19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 20 */
 21
 22#include <ndn-cxx/face.hpp>
 23#include <ndn-cxx/security/validator-config.hpp>
 24
 25#include <iostream>
 26
 27// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
 28namespace ndn {
 29// Additional nested namespaces should be used to prevent/limit name conflicts
 30namespace examples {
 31
 32class Consumer
 33{
 34public:
 35  Consumer()
 36  {
 37    m_validator.load("trust-schema.conf");
 38  }
 39
 40  void
 41  run()
 42  {
 43    Name interestName("/example/testApp/randomData");
 44    interestName.appendVersion();
 45
 46    Interest interest(interestName);
 47    interest.setCanBePrefix(false);
 48    interest.setMustBeFresh(true);
 49    interest.setInterestLifetime(6_s); // The default is 4 seconds
 50
 51    std::cout << "Sending Interest " << interest << std::endl;
 52    m_face.expressInterest(interest,
 53                           std::bind(&Consumer::onData, this,  _1, _2),
 54                           std::bind(&Consumer::onNack, this, _1, _2),
 55                           std::bind(&Consumer::onTimeout, this, _1));
 56
 57    // processEvents will block until the requested data is received or a timeout occurs
 58    m_face.processEvents();
 59  }
 60
 61private:
 62  void
 63  onData(const Interest&, const Data& data)
 64  {
 65    std::cout << "Received Data " << data << std::endl;
 66
 67    m_validator.validate(data,
 68                         [] (const Data&) {
 69                           std::cout << "Data conforms to trust schema" << std::endl;
 70                         },
 71                         [] (const Data&, const security::ValidationError& error) {
 72                           std::cout << "Error authenticating data: " << error << std::endl;
 73                         });
 74  }
 75
 76  void
 77  onNack(const Interest&, const lp::Nack& nack) const
 78  {
 79    std::cout << "Received Nack with reason " << nack.getReason() << std::endl;
 80  }
 81
 82  void
 83  onTimeout(const Interest& interest) const
 84  {
 85    std::cout << "Timeout for " << interest << std::endl;
 86  }
 87
 88private:
 89  Face m_face;
 90  ValidatorConfig m_validator{m_face};
 91};
 92
 93} // namespace examples
 94} // namespace ndn
 95
 96int
 97main(int argc, char** argv)
 98{
 99  try {
100    ndn::examples::Consumer consumer;
101    consumer.run();
102    return 0;
103  }
104  catch (const std::exception& e) {
105    std::cerr << "ERROR: " << e.what() << std::endl;
106    return 1;
107  }
108}

Trivial producer

The following example demonstrates how to write a simple producer application.

First, the application sets an Interest filter for /localhost/testApp to receive all Interests that have this prefix. The Face::setInterestFilter() call accepts two callbacks; the first will be called when an Interest is received and the second if prefix registration fails.

After an Interest is received, the producer creates a Data packet with the same name as the received Interest, adds content, and signs it with the system-default identity. It is also possible to specify a particular key to be used during the signing. For more information, refer to KeyChain API documentation.

Finally, after Data packet has been created and signed, it is returned to the requester using Face::put() method.

  1/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
  2/*
  3 * Copyright (c) 2013-2021 Regents of the University of California.
  4 *
  5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  6 *
  7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
  8 * terms of the GNU Lesser General Public License as published by the Free Software
  9 * Foundation, either version 3 of the License, or (at your option) any later version.
 10 *
 11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 13 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 14 *
 15 * You should have received copies of the GNU General Public License and GNU Lesser
 16 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 17 * <http://www.gnu.org/licenses/>.
 18 *
 19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 20 */
 21
 22#include <ndn-cxx/face.hpp>
 23#include <ndn-cxx/security/key-chain.hpp>
 24#include <ndn-cxx/security/signing-helpers.hpp>
 25
 26#include <iostream>
 27
 28// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
 29namespace ndn {
 30// Additional nested namespaces should be used to prevent/limit name conflicts
 31namespace examples {
 32
 33class Producer
 34{
 35public:
 36  void
 37  run()
 38  {
 39    m_face.setInterestFilter("/example/testApp/randomData",
 40                             std::bind(&Producer::onInterest, this, _1, _2),
 41                             nullptr, // RegisterPrefixSuccessCallback is optional
 42                             std::bind(&Producer::onRegisterFailed, this, _1, _2));
 43
 44    auto cert = m_keyChain.getPib().getDefaultIdentity().getDefaultKey().getDefaultCertificate();
 45    m_certServeHandle = m_face.setInterestFilter(security::extractIdentityFromCertName(cert.getName()),
 46                             [this, cert] (auto&&...) {
 47                               m_face.put(cert);
 48                             },
 49                             std::bind(&Producer::onRegisterFailed, this, _1, _2));
 50    m_face.processEvents();
 51  }
 52
 53private:
 54  void
 55  onInterest(const InterestFilter&, const Interest& interest)
 56  {
 57    std::cout << ">> I: " << interest << std::endl;
 58
 59    static const std::string content("Hello, world!");
 60
 61    // Create Data packet
 62    auto data = make_shared<Data>(interest.getName());
 63    data->setFreshnessPeriod(10_s);
 64    data->setContent(reinterpret_cast<const uint8_t*>(content.data()), content.size());
 65
 66    // in order for the consumer application to be able to validate the packet, you need to setup
 67    // the following keys:
 68    // 1. Generate example trust anchor
 69    //
 70    //         ndnsec key-gen /example
 71    //         ndnsec cert-dump -i /example > example-trust-anchor.cert
 72    //
 73    // 2. Create a key for the producer and sign it with the example trust anchor
 74    //
 75    //         ndnsec key-gen /example/testApp
 76    //         ndnsec sign-req /example/testApp | ndnsec cert-gen -s /example -i example | ndnsec cert-install -
 77
 78    // Sign Data packet with default identity
 79    m_keyChain.sign(*data);
 80    // m_keyChain.sign(*data, signingByIdentity(<identityName>));
 81    // m_keyChain.sign(*data, signingByKey(<keyName>));
 82    // m_keyChain.sign(*data, signingByCertificate(<certName>));
 83    // m_keyChain.sign(*data, signingWithSha256());
 84
 85    // Return Data packet to the requester
 86    std::cout << "<< D: " << *data << std::endl;
 87    m_face.put(*data);
 88  }
 89
 90  void
 91  onRegisterFailed(const Name& prefix, const std::string& reason)
 92  {
 93    std::cerr << "ERROR: Failed to register prefix '" << prefix
 94              << "' with the local forwarder (" << reason << ")" << std::endl;
 95    m_face.shutdown();
 96  }
 97
 98private:
 99  Face m_face;
100  KeyChain m_keyChain;
101  ScopedRegisteredPrefixHandle m_certServeHandle;
102};
103
104} // namespace examples
105} // namespace ndn
106
107int
108main(int argc, char** argv)
109{
110  try {
111    ndn::examples::Producer producer;
112    producer.run();
113    return 0;
114  }
115  catch (const std::exception& e) {
116    std::cerr << "ERROR: " << e.what() << std::endl;
117    return 1;
118  }
119}

Consumer that uses Scheduler

The following example demonstrates how to use Scheduler to schedule arbitrary events for execution at specific points of time.

The library internally uses boost::asio::io_service to implement fully asynchronous NDN operations (i.e., sending and receiving Interests and Data). In addition to network-related operations, boost::asio::io_service can be used to execute any arbitrary callback within the processing thread (run either explicitly via io_service::run() or implicitly via Face::processEvents() as in previous examples). Scheduler is just a wrapper on top of io_service, providing a simple interface to schedule tasks at specific times.

The highlighted lines in the example demonstrate all that is needed to express a second Interest approximately 3 seconds after the first one.

  1/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */
  2/*
  3 * Copyright (c) 2013-2021 Regents of the University of California.
  4 *
  5 * This file is part of ndn-cxx library (NDN C++ library with eXperimental eXtensions).
  6 *
  7 * ndn-cxx library is free software: you can redistribute it and/or modify it under the
  8 * terms of the GNU Lesser General Public License as published by the Free Software
  9 * Foundation, either version 3 of the License, or (at your option) any later version.
 10 *
 11 * ndn-cxx library is distributed in the hope that it will be useful, but WITHOUT ANY
 12 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
 13 * PARTICULAR PURPOSE.  See the GNU Lesser General Public License for more details.
 14 *
 15 * You should have received copies of the GNU General Public License and GNU Lesser
 16 * General Public License along with ndn-cxx, e.g., in COPYING.md file.  If not, see
 17 * <http://www.gnu.org/licenses/>.
 18 *
 19 * See AUTHORS.md for complete list of ndn-cxx authors and contributors.
 20 */
 21
 22#include <ndn-cxx/face.hpp>
 23#include <ndn-cxx/util/scheduler.hpp>
 24
 25#include <boost/asio/io_service.hpp>
 26#include <iostream>
 27
 28// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
 29namespace ndn {
 30// Additional nested namespaces should be used to prevent/limit name conflicts
 31namespace examples {
 32
 33class ConsumerWithTimer
 34{
 35public:
 36  ConsumerWithTimer()
 37    : m_face(m_ioService) // Create face with io_service object
 38    , m_scheduler(m_ioService)
 39  {
 40  }
 41
 42  void
 43  run()
 44  {
 45    Name interestName("/example/testApp/randomData");
 46    interestName.appendVersion();
 47
 48    Interest interest(interestName);
 49    interest.setCanBePrefix(false);
 50    interest.setMustBeFresh(true);
 51    interest.setInterestLifetime(2_s);
 52
 53    std::cout << "Sending Interest " << interest << std::endl;
 54    m_face.expressInterest(interest,
 55                           std::bind(&ConsumerWithTimer::onData, this, _1, _2),
 56                           std::bind(&ConsumerWithTimer::onNack, this, _1, _2),
 57                           std::bind(&ConsumerWithTimer::onTimeout, this, _1));
 58
 59    // Schedule a new event
 60    m_scheduler.schedule(3_s, [this] { delayedInterest(); });
 61
 62    // m_ioService.run() will block until all events finished or m_ioService.stop() is called
 63    m_ioService.run();
 64
 65    // Alternatively, m_face.processEvents() can also be called.
 66    // processEvents will block until the requested data received or timeout occurs.
 67    // m_face.processEvents();
 68  }
 69
 70private:
 71  void
 72  onData(const Interest&, const Data& data) const
 73  {
 74    std::cout << "Received Data " << data << std::endl;
 75  }
 76
 77  void
 78  onNack(const Interest& interest, const lp::Nack& nack) const
 79  {
 80    std::cout << "Received Nack with reason " << nack.getReason()
 81              << " for " << interest << std::endl;
 82  }
 83
 84  void
 85  onTimeout(const Interest& interest) const
 86  {
 87    std::cout << "Timeout for " << interest << std::endl;
 88  }
 89
 90  void
 91  delayedInterest()
 92  {
 93    std::cout << "One more Interest, delayed by the scheduler" << std::endl;
 94
 95    Name interestName("/example/testApp/randomData");
 96    interestName.appendVersion();
 97
 98    Interest interest(interestName);
 99    interest.setCanBePrefix(false);
100    interest.setMustBeFresh(true);
101    interest.setInterestLifetime(2_s);
102
103    std::cout << "Sending Interest " << interest << std::endl;
104    m_face.expressInterest(interest,
105                           std::bind(&ConsumerWithTimer::onData, this, _1, _2),
106                           std::bind(&ConsumerWithTimer::onNack, this, _1, _2),
107                           std::bind(&ConsumerWithTimer::onTimeout, this, _1));
108  }
109
110private:
111  // Explicitly create io_service object, which will be shared between Face and Scheduler
112  boost::asio::io_service m_ioService;
113  Face m_face;
114  Scheduler m_scheduler;
115};
116
117} // namespace examples
118} // namespace ndn
119
120int
121main(int argc, char** argv)
122{
123  try {
124    ndn::examples::ConsumerWithTimer consumer;
125    consumer.run();
126    return 0;
127  }
128  catch (const std::exception& e) {
129    std::cerr << "ERROR: " << e.what() << std::endl;
130    return 1;
131  }
132}