如何在C++中使用openDHT获取存储数据 代码读取失效问题
openDHT C++ 数据存储与读取问题修复
故障原因
- 节点未完成启动引导就执行读写操作:
node.bootstrap()为异步接口,调用后节点需要完成网络握手、路由表同步,此时执行的put/get请求会直接失败。 - 查询键格式不匹配:存储时使用
dht::InfoHash::get()将输入字符串转为哈希对象作为键,查询时直接传入原始字符串,未做哈希转换,查询目标和存储目标完全不一致。 - 异步操作无等待逻辑:
put提交后需要时间将数据同步到对应路由节点,get提交后需要等待网络返回结果,原代码提交查询请求后直接调用node.join(),程序可能在拿到回调前就退出。 - 缺失编译依赖头文件:使用
std::cout/std::cin未引入<iostream>,部分编译环境下会直接报错无法运行。 - 无效的本地bootstrap配置:当前节点已监听4222端口,再执行
bootstrap("localhost", "4222")相当于自连,单节点测试场景下该配置无实际作用。
修复后可运行代码
#include <cstdio> #include <cstdlib> #include <vector> #include <cstring> #include <iostream> #include <thread> #include <chrono> #include <opendht.h> int main(int argc, char ** argv) { dht::DhtRunner node; node.run(4222, dht::crypto::generateIdentity(), true); // 等待节点完成初始化、网络栈加载 std::this_thread::sleep_for(std::chrono::seconds(5)); std::string buffer; bool running = true; while(running) { std::cout << "输入a存储数据,输入q退出: "; buffer.clear(); std::cin >> buffer; switch(buffer.c_str()[0]) { case 'a': case 'A': { std::cout << "请输入键: "; buffer.clear(); std::cin >> buffer; dht::InfoHash key_hash = dht::InfoHash::get(buffer.c_str()); node.put(key_hash, "dummy"); // 等待put操作同步完成 std::this_thread::sleep_for(std::chrono::seconds(2)); std::cout << "数据存储提交完成" << std::endl; break; } case 'q': case 'Q': running = false; break; default: std::cout << "!!! 未知选项 !!!" << std::endl; } } std::cout << "请输入要查询的键: "; buffer.clear(); std::cin >> buffer; dht::InfoHash query_hash = dht::InfoHash::get(buffer.c_str()); bool got_result = false; node.get(query_hash, [&got_result](const std::vector<std::shared_ptr<dht::Value>>& values) { for (const auto& value : values) { std::cout << "找到值: " << value->toString() << std::endl; } got_result = true; return true; }); // 最长等待10秒查询结果,避免程序提前退出 auto start = std::chrono::steady_clock::now(); while(!got_result && std::chrono::duration_cast<std::chrono::seconds>(std::chrono::steady_clock::now() - start).count() < 10) { std::this_thread::sleep_for(std::chrono::milliseconds(100)); } node.join(); return 0; }
运行注意事项
- 多节点组网测试时,需通过
bootstrap连接可用的公共DHT引导节点,确保节点能接入公共DHT网络。 - openDHT所有网络操作均为异步实现,提交读写请求后必须预留足够的网络交互时间,不能立即退出程序。
- 操作返回的
dht::Value为智能指针封装,建议通过成员方法获取存储内容,避免直接解引用空指针。
内容的提问来源于stack exchange,提问作者Imron Gamidli
相关产品推荐
相关产品推荐

