Basic examples

Trivial consumer

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

ndn::bind is an alias for either boost::bind or std::bind when the library is compiled in C++11 mode.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (c) 2013-2014 Regents of the University of California.
 * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
 * BSD License, see COPYING for copyright and distribution information.
 */

// correct way to include NDN-CPP headers
// #include <ndn-cpp-dev/face.hpp>
#include "face.hpp"

// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {

void
onData(Face& face,
       const Interest& interest, Data& data)
{
  std::cout << "I: " << interest.toUri() << std::endl;
  std::cout << "D: " << data.getName().toUri() << std::endl;
}

void
onTimeout(Face& face,
          const Interest& interest)
{
  std::cout << "Timeout" << std::endl;
}

int
main(int argc, char** argv)
{
  try {
    Interest i(Name("/localhost/testApp/randomData"));
    i.setScope(1);
    i.setInterestLifetime(time::milliseconds(1000));
    i.setMustBeFresh(true);

    Face face;
    face.expressInterest(i,
                         bind(onData, boost::ref(face), _1, _2),
                         bind(onTimeout, boost::ref(face), _1));

    // processEvents will block until the requested data received or timeout occurs
    face.processEvents();
  }
  catch(std::exception& e) {
    std::cerr << "ERROR: " << e.what() << std::endl;
    return 1;
  }
  return 0;
}

} // namespace examples
} // namespace ndn

int
main(int argc, char** argv)
{
  return ndn::examples::main(argc, argv);
}

Trivial producer

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

First, application sets interset filter for /localhost/testApp to receive all Interests that have this prefix. setInterestFilter call accepts two callbacks, one which will be called when an Interest is received, and the other if prefix registration (i.e., configuring proper FIB entry in NFD) fails.

After Interest is received, a producer creates a Data packet with the same name as in the received Interest, adds a silly content, and signs the Data packet with the system-default identity. It is 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
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (c) 2013-2014 Regents of the University of California.
 * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
 * BSD License, see COPYING for copyright and distribution information.
 */

// correct way to include NDN-CPP headers
// #include <ndn-cpp-dev/face.hpp>
// #include <ndn-cpp-dev/security/key-chain.hpp>

#include "face.hpp"
#include "security/key-chain.hpp"

// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {

class Producer
{
public:
  void
  onInterest(const Name& name, const Interest& interest)
  {
    std::cout << "<< I: " << interest << std::endl;

    // Create new name, based on Interest's name
    Name dataName(interest.getName());
    dataName
      .append("testApp") // add "testApp" component to Interest name
      .appendVersion();  // add "version" component (current UNIX timestamp in milliseconds)

    static const std::string content = "HELLO KITTY";

    // Create Data packet
    Data data;
    data.setName(dataName);
    data.setFreshnessPeriod(time::seconds(10));
    data.setContent(reinterpret_cast<const uint8_t*>(content.c_str()), content.size());

    // Sign Data packet with default identity
    m_keyChain.sign(data);
    // m_keyChain.sign(data, <identityName>);
    // m_keyChain.sign(data, <certificate>);

    // Return Data packet to the requester
    std::cout << ">> D: " << data << std::endl;
    m_face.put(data);
  }


  void
  onRegisterFailed(const Name& prefix, const std::string& reason)
  {
    std::cerr << "ERROR: Failed to register prefix in local hub's daemon (" << reason << ")"
              << std::endl;
    m_face.shutdown();
  }

  void
  run()
  {
    m_face.setInterestFilter("/localhost/testApp",
                             bind(&Producer::onInterest, this, _1, _2),
                             bind(&Producer::onRegisterFailed, this, _1, _2));
    m_face.processEvents();
  }

private:
  Face m_face;
  KeyChain m_keyChain;
};

} // namespace examples
} // namespace ndn

int
main(int argc, char** argv)
{
  try {
    ndn::examples::Producer producer;
    producer.run();
  }
  catch (std::exception& e) {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }
  return 0;
}

Consumer that uses ndn::Scheduler

The following example demonstrates use for ndn::Scheduler to schedule an 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->run or implicitly via Face::processEvents as in previous examples). ndn::Scheduler is just a wrapper on top of boost::asio::io_service, allowing 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 2 seconds after the first one.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
/* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil -*- */
/**
 * Copyright (c) 2013-2014 Regents of the University of California.
 * @author: Alexander Afanasyev <alexander.afanasyev@ucla.edu>
 * BSD License, see COPYING for copyright and distribution information.
 */

// correct way to include NDN-CPP headers
// #include <ndn-cpp-dev/face.hpp>
// #include <ndn-cpp-dev/util/scheduler.hpp>
#include "face.hpp"
#include "util/scheduler.hpp"

// Enclosing code in ndn simplifies coding (can also use `using namespace ndn`)
namespace ndn {
// Additional nested namespace could be used to prevent/limit name contentions
namespace examples {

void
onData(Face& face,
       const Interest& interest, Data& data)
{
  std::cout << "I: " << interest.toUri() << std::endl;
  std::cout << "D: " << data.getName().toUri() << std::endl;
}

void
onTimeout(Face& face,
          const Interest& interest)
{
  std::cout << "Timeout" << std::endl;
}

void
delayedInterest(Face& face)
{
  std::cout << "One more Interest, delayed by the scheduler" << std::endl;

  Interest i(Name("/localhost/testApp/randomData"));
  i.setScope(1);
  i.setInterestLifetime(time::milliseconds(1000));
  i.setMustBeFresh(true);

  face.expressInterest(i,
                       bind(&onData, boost::ref(face), _1, _2),
                       bind(&onTimeout, boost::ref(face), _1));
}

int
main(int argc, char** argv)
{
  try {
    // Explicitly create io_service object, which can be shared between Face and Scheduler
    shared_ptr<boost::asio::io_service> io = make_shared<boost::asio::io_service>();

    Interest i(Name("/localhost/testApp/randomData"));
    i.setScope(1);
    i.setInterestLifetime(time::seconds(1));
    i.setMustBeFresh(true);

    // Create face with io_service object
    Face face(io);
    face.expressInterest(i,
                         bind(&onData, boost::ref(face), _1, _2),
                         bind(&onTimeout, boost::ref(face), _1));


    // Create scheduler object
    Scheduler scheduler(*io);

    // Schedule a new event
    scheduler.scheduleEvent(time::seconds(2),
                            bind(&delayedInterest, boost::ref(face)));

    // io->run() will block until all events finished or io->stop() is called
    io->run();

    // Alternatively, a helper face.processEvents() also can be called
    // processEvents will block until the requested data received or timeout occurs
    // face.processEvents();
  }
  catch(std::exception& e) {
    std::cerr << "ERROR: " << e.what() << std::endl;
  }
  return 0;
}

} // namespace examples
} // namespace ndn

int
main(int argc, char** argv)
{
  return ndn::examples::main(argc, argv);
}