// // Created by sunny on 2020/7/24. // #include #include #include #include #include // Enclosing code in ndn simplifies coding (can also use `using namespace ndn`) namespace ndn { // Additional nested namespaces can be used to prevent/limit name conflicts namespace examples { class Consumer : noncopyable { public: void run() { Interest interest(Name("/test/hello/" + std::to_string(1))); // 如果需要传递参数,可以通过一下方式传递 std::string param = "{\"code\": 1, \"msg\": \"balabala\"}"; interest.setApplicationParameters(reinterpret_cast(param.data()), param.size()); // 设置兴趣包的生存期,超过这个生存期没有收到对应的数据包,兴趣包就会触发超时 interest.setInterestLifetime(2_s); // 2 seconds // 设置如果强制刷新,则不会命中途中路由器的缓存 interest.setMustBeFresh(true); interest.setTag(make_shared(1)); interest.setTag(make_shared(2)); auto srcTag = make_shared(lp::SrcAddrHeader(Name("/testSrcAddr"))); interest.setTag(srcTag); srcTag->get().getMyPrefix()->wireEncode(); interest.setTag(make_shared(lp::DstAddrHeader(Name("/testDstAddr")))); interest.setTag(make_shared(lp::BackupNameHeader(Name("/testBackupName")))); auto cachePolicy = lp::CachePolicy(); cachePolicy.setPolicy(lp::CachePolicyType::NO_CACHE); interest.setTag(make_shared(cachePolicy)); // 发送兴趣包 m_face.expressInterest(interest, bind(&Consumer::onData, this, _1, _2), bind(&Consumer::onNack, this, _1, _2), bind(&Consumer::onTimeout, this, _1)); std::cout << "Sending " << interest << std::endl; // 需要调用processEvents处理NDN事件,这样才能处理收到的数据包,要不然程序就直接退出了 // 这个操作会一直阻塞,直到处理完所有的NDN事件 // processEvents will block until the requested data received or timeout occurs m_face.processEvents(); } private: void onData(const Interest &interest, const Data &data) { std::cout << data << std::endl; } void onNack(const Interest &interest, const lp::Nack &nack) { std::cout << "received Nack with reason " << nack.getReason() << " for interest " << interest << std::endl; } void onTimeout(const Interest &interest) { std::cout << "Timeout " << interest << std::endl; } private: Face m_face; }; } // namespace examples } // namespace ndn int main(int argc, char **argv) { ndn::examples::Consumer consumer; try { consumer.run(); } catch (const std::exception &e) { std::cerr << "ERROR: " << e.what() << std::endl; } return 0; }